ingh.am
ingh.am

Reputation: 26822

Setup a TCP listener in PHP

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

Upvotes: 2

Views: 4515

Answers (1)

vstm
vstm

Reputation: 12537

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):

// ... 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
}

Now you could implement the "handleMessage" function which analyses the response and acts to it.

Upvotes: 3

Related Questions