php - 在 PHP 中设置 TCP 监听器

标签 php json sockets fsockopen tcplistener

我们目前使用的系统通过 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 监听器?

谢谢

最佳答案

要创建监听套接字,请使用以下函数:

我不确定 fwrite()/fread() 是否正在使用这些套接字,否则您必须使用以下函数:

消息循环

我现在已经编写了一些函数来读取单个 JSON 响应,并假设多个响应由 CRLF 分隔。 这是我的做法(假设你的 php 脚本有无限的执行时间):

// ... your code ... 

function readJson($socket) {
    $readData = true;
    $jsonString = '';
    while(true) {
        $chunk = fgets($socket, 2048); 
        $jsonString .= $chunk;

        if(($json = json_decode($jsonString)) !== false) {
            return $json;
        } elseif(empty($chunk)) {
            // eof
            return false;
        }
    }
}

// ....
// Now call a test method request
fwrite($socket, $jsonMethodRequest);

$execMessageLoop = true;
while($execMessageLoop) {
    $response = readJson($socket);
    if($response === false) {
        $execMessageLoop = false;
    } else {
        handleMessage($socket, $response);
    }
}

function handleMessage($socket, $response) {
    // do what you have to do
}

现在您可以实现“handleMessage”函数来分析响应并对其采取行动。

关于php - 在 PHP 中设置 TCP 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6957071/

相关文章:

php - 如何使用 Laravel Eloquent 创建多个 Where 子句查询?

javascript - JSON key 作为时间

networking - 将单个端口用于多个套接字的标准方法?

php - 具有多条记录的 LAST_INSERT_ID() 插入 MySQL

php - 在多个 "NOT IN"子句中使用变量

php - 在 php 中只运行一次代码

ruby-on-rails - 解析参数时发生Rails错误

c# - 使用 EntityFramework 在 MVC 中以 JSON 形式返回具有导航属性的实体的最佳实践

c++ - 在 C/C++ 中使用异步套接字时检测远程断开(半关闭)

python - 简单 python 服务器的问题。即使在我(据说)关闭套接字之后,socket.accept() 仍接受 input/favicon.ico