我有一个连接到服务器的web服务,并以xml或json的形式返回结果。它是用 asp.net 写的。我想在 php 中使用相同的方法。
using (TcpClient tcpClient = new TcpClient())
{
tcpClient.Connect("1.1.1.1", port: 42011);
string search = "search^10|5|2|1^gagl^55592a782ce899d2" +
System.Environment.NewLine;
using (NetworkStream ns = tcpClient.GetStream())
{
byte[] bytes = ASCIIEncoding.ASCII.GetBytes(search);
ns.Write(bytes, 0, bytes.Length);
string result = ReadBuffer(ns);
// [.. consume result XML string ..]
}
tcpClient.Close();
}
}
protected string ReadBuffer(NetworkStream ns)
{
byte[] lenghtBuffer = new byte[4];
int bytesRead = 0;
while (bytesRead < 4)
bytesRead += ns.Read(lenghtBuffer, bytesRead, 4 - bytesRead);
if (BitConverter.IsLittleEndian)
Array.Reverse(lenghtBuffer);
int responseLength = BitConverter.ToInt32(lenghtBuffer, 0);
byte[] buffer = new byte[responseLength];
bytesRead = 0;
while (bytesRead < responseLength)
bytesRead += ns.Read(buffer, bytesRead, responseLength - bytesRead);
string result = ASCIIEncoding.ASCII.GetString(buffer, 0, bytesRead);
return result;
}
上面的代码返回 .net 中的值。如何使用相同的值在 php 中获取结果。
您可以使用 fsockopen (http://php.net/manual/fr/function.fsockopen.php) 打开 TCP 连接并检索结果。