Is there a way to listen for new socket connections while doing a do, while loop in PHP?

Viewed 214

I am trying to make a simple PHP, javascript websocket test project and I ran into the issue where PHP would not continue the while(true) loop once I call the socket accept function. It waits for an actual connection before continuing the loop. Is there a way to call this asynchronously so the while loop can continue? Or is there a way to immediately accept more incoming connections after one is accepted? Here is my code

<?php
error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. 
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
as it comes in. 
ob_implicit_flush();*/
$address = 'localhost';
$port = 8080;
$clients = [];
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($server, $address, $port);
socket_listen($server);
/*$client = acceptConn($server);
$clients[0] = $client;*/

// Send WebSocket handshake headers.

$newclient = socket_accept($server);
handshake($server, $newclient);
$clients[count($clients)] = $newclient;

function handshake($server, $client){
    $request = socket_read($client, 5000);
preg_match('#Sec-WebSocket-Key: (.*)\r\n#', $request, $matches);
$key = base64_encode(pack(
    'H*',
    sha1($matches[1] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
));
$headers = "HTTP/1.1 101 Switching Protocols\r\n";
$headers .= "Upgrade: websocket\r\n";
$headers .= "Connection: Upgrade\r\n";
$headers .= "Sec-WebSocket-Version: 13\r\n";
$headers .= "Sec-WebSocket-Accept: $key\r\n\r\n";
socket_write($client, $headers, strlen($headers));
}


// Send messages into WebSocket in a loop.
 do {
    sleep(1);
    //echo "next";
    $content = 'Now: ' . time();
    $response = chr(129) . chr(strlen($content)) . $content;

    


    foreach($clients as $key => $item){
        if(socket_write($item, $response) != 17){
            socket_close($item);
            unset($clients[$key]);
            continue;
            //echo json_encode($clients);
        }
        continue;
    }
    /*echo count($clients);
    $newclient = socket_accept($server);
    echo gettype($newclient);
    $clients[count($clients)] = $client;*/
    
    
    
    
}while (true);


?>
1 Answers

I found the solution. To anyone who was wondering what it was, use:

socket_set_nonblock($socketservervariable);

to make the server not wait for a client to connect before proceeding. That creates a new error though. When doing the client handshake the socket_read wanted a socket but it got the boolean value of false when the socket_accept function didn't detect a client connecting. So this was my solution to that:

$newclient = socket_accept($server);
if($newclient != false){
    handshake($server, $newclient);
    $clients[count($clients)] = $newclient;
    echo "\n\nNew client connected!\n\n";
}

and that solved all of my problems.

Related