PHP TCP socket server hangs when accepting a new connection

573 views Asked by At

I'm trying to set up a TCP socket server, which should support many client connections at the same time, together with receiving and sending data.

For this purpose I'm trying to use PHP's socket_select(); due to server always hanged on socket_read(); process, where it should continue, no matter if there were data, or not. I Tried to run following code below, but it always hangs on a new client connection.

// TCP socket created
$clients = array($socket);
while (true) { // Infinite loop for server
   $newsock = socket_accept($socket);
   if ($newsock !== false) {
      // Adds a new client
      $clients[] = $newsock;
   }
   $read = $clients;
   $write = NULL;
   $except = NULL;
   $num_changed_sockets = socket_select($read, $write, $except, 0);
   if ($num_changed_sockets === false) {
      // Error here
   } else if ($num_changed_sockets > 0) {
      // Something happened
      if (in_array($socket, $read)) {
         $key = array_search($socket, $read);
         unset($read($key]);
      }
      foreach ($read as $read_socket) {
         $data = socket_read($read_socket, 128); // This should not hang!
         if ($data === false) {
            // Disconnect client
         }
         // Reads data, sends answer...
      }
   }
   // Something to send for all clients
}

Is it also possible to use socket_select(); without having a copy of my clients in an array, where the listener is included? Just having a clean array for clients.

2

There are 2 answers

1
Some programmer dude On

Sockets are by default blocking, you should put the passive listening socket ($socket in your case) in the read set passed to socket_select as well, and it will be readable when you can accept new connections.

0
Mikael H. On

Just set the listening socket $socket to non-blocking mode. Clients get connected and data is being read, but the client disconnects are not handled in real time (there is a pretty big delay on it). Is there reason for that?