//manage multiple connections $changed = $clients; //returns the socket resources in $changed array if (count($changed) > 0) { socket_select($changed, $null, $null, 0); } //check for new socket if (in_array($sock, $changed)) { $socket_new = socket_accept($sock); //accept new socket $clients[] = $socket_new; //add socket to client array $found_socket = array_search($socket_new, $clients); $header = socket_read($socket_new, 1024); //read data sent by the socket perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake socket_getpeername($socket_new, $address, $port); //get ip address of connected socket $address_clients[$found_socket] = $address; $found_socket = array_search($sock, $changed); echo "Client[{$address}] connected to us on port {$port}\n"; //make room for new socket unset($changed[$found_socket]); } //loop through all connected sockets foreach ($changed as $changed_socket) { //check for any incomming data while (socket_recv($changed_socket, $buf, 1024, 0) >= 1) { $received_text = unmask($buf); //unmask data
$host = 'localhost'; $port = '3000'; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind($socket, 0, $port); socket_listen($socket); $clients = array($socket); while (true) { $changed = $clients; socket_select($changed, NULL, NULL, 0, 10); if (in_array($socket, $changed)) { $newSocket = socket_accept($socket); $clients[] = $newSocket; $header = socket_read($newSocket, 1024); perform_handshaking($header, $newSocket, $host, $port); socket_getpeername($newSocket, $ip); $found_socket = array_search($socket, $changed); unset($changed[$found_socket]); } foreach ($changed as $changed_socket) { while (socket_recv($changed_socket, $buf, 1024, 0) >= 1) { $received_text = unmask($buf); $tst_msg = json_decode($received_text); $posx = $tst_msg->posx; $posy = $tst_msg->posy; $response_text = mask(json_encode(array('posx' => $posx, 'posy' => $posy))); send_message($response_text); break 2; } $buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ);