php中的tcp客户端连接
我有一个Web服务,它连接到服务器并以xml或json的形式返回结果。它是用asp.net编写的。我想在php中使用同样的方法php中的tcp客户端连接,php,tcp,connection,Php,Tcp,Connection,我有一个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.Environ
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;
}
使用(TcpClient TcpClient=new TcpClient())
{
TCP客户端连接(“1.1.1.1”,端口:42011);
string search=“搜索^10 | 5 | 2 | 1^gagl^55592a782ce899d2”+
System.Environment.NewLine;
使用(NetworkStream ns=tcpClient.GetStream())
{
byte[]bytes=ascienceoding.ASCII.GetBytes(搜索);
ns.Write(字节,0,字节.长度);
字符串结果=读取缓冲区(ns);
//[…使用结果XML字符串..]
}
tcpClient.Close();
}
}
受保护的字符串读取缓冲区(NetworkStream ns)
{
字节[]lenghtBuffer=新字节[4];
int字节读取=0;
while(字节数<4)
bytesRead+=ns.Read(lenghtBuffer,bytesRead,4-bytesRead);
if(位转换器.IsLittleEndian)
Array.Reverse(lenghtBuffer);
int responseLength=位转换器.ToInt32(长度缓冲区,0);
字节[]缓冲区=新字节[responseLength];
字节读取=0;
while(字节读取<响应长度)
bytesRead+=ns.Read(缓冲区、bytesRead、响应长度-bytesRead);
字符串结果=ascienceoding.ASCII.GetString(缓冲区,0,字节读取);
返回结果;
}
上述代码返回.net中的值。如何使用相同的值在php中获得结果。您可以使用fsockopen()打开TCP连接并检索结果。这不起作用。我尝试了。这不起作用是的,我可以通过端口连接到ip。我也得到了回应——“403未经授权访问”。这是因为字符串“search^10 | 5 | 2 | 1 ^gagl^55592a782ce899d2”未正确传递。55592a782ce899d2这是服务器将验证的值。@[403]请求被拒绝:您无权使用此服务