在 PHP 中设置 TCP 监听器
我们目前使用的系统通过 TCP 接收传入的 JSON 请求并也使用 JSON 进行响应。目前,我已经在 PHP 中像这样设置了套接字:
$socket = fsockopen($host, $port, $errno, $errstr, $timeout);
if(!$socket)
{
fwrite($socket, $jsonLoginRequest); // Authentication JSON
while(json_decode($loginResponse) == false) // We know we have all packets when it's valid JSON.
{
$loginResponse .= fgets($socket, 128);
}
// We are now logged in.
// Now call a test method request
fwrite($socket, $jsonMethodRequest);
while(json_decode($methodResponse) == false) // We know we have all packets when it's valid JSON.
{
$methodResponse .= fgets($socket, 128);
echo $methodResponse; // print response out
}
// Now we have the response to our method request.
fclose($socket);
}
else
{
// error with socket
}
目前可以正常工作,并且服务器响应方法请求。然而,有些方法会像这样响应来确认调用,但稍后也会响应我所追求的结果。所以我真正需要的是一个 TCP 监听器。谁能建议我如何像上面那样使用 fsock 编写 TCP 侦听器?
谢谢
We're using a system at the moment that takes an incoming JSON request over TCP and responds using JSON too. Currently I've set up my socket like so in PHP:
$socket = fsockopen($host, $port, $errno, $errstr, $timeout);
if(!$socket)
{
fwrite($socket, $jsonLoginRequest); // Authentication JSON
while(json_decode($loginResponse) == false) // We know we have all packets when it's valid JSON.
{
$loginResponse .= fgets($socket, 128);
}
// We are now logged in.
// Now call a test method request
fwrite($socket, $jsonMethodRequest);
while(json_decode($methodResponse) == false) // We know we have all packets when it's valid JSON.
{
$methodResponse .= fgets($socket, 128);
echo $methodResponse; // print response out
}
// Now we have the response to our method request.
fclose($socket);
}
else
{
// error with socket
}
This works at the moment, and the server responds to the method request. However, some methods will respond like this to acknowledge the call, but will also respond later on with the results I'm after. So what I really need is a TCP listener. Could anyone advise how I could write a TCP listener using fsock like I have above?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要创建监听套接字,请使用以下函数:
我不确定是否
fwrite()
/fread()
正在使用这些套接字,否则您必须使用以下函数:消息循环
我现在编写了一些函数来读取单个 JSON 响应,并假设多个响应由 CRLF 分隔。
我将这样做(假设您的 php 脚本具有无限的执行时间):
现在您可以实现“handleMessage”函数,该函数分析响应并对其进行操作。
To create a listening socket use the following functions:
I'm not shure if
fwrite()
/fread()
are working with those sockets otherwise you have to use the following functions:Message-loop
I have now written some function to read a single JSON responses with the assumption that multiple responses are separated by CRLF.
Here's how I would do it (assuming your php-script has unlimited execution time):
Now you could implement the "handleMessage" function which analyses the response and acts to it.