2

我们目前正在使用一个系统,该系统通过 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 侦听器?

谢谢

4

1 回答 1

3

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

我不确定是否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”函数来分析响应并对其采取行动。

于 2011-08-05T13:40:15.027 回答