简体   繁体   中英

PHP TCP socket server hangs when accepting a new connection

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.

默认情况下,套接字是阻塞的 ,您也应该将被动侦听套接字(在您的情况下$socket )放入传递给socket_select的读取集中,当您可以接受新连接时,它将可读。

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM