Jump to content

[SOLVED] multiple clients to a socket server


Recommended Posts

Hey,

 

I have made a simple socket server in PHP which accepts connections and takes text commands to do different actions. My problem is that  it only responds to the first connection of many, I need it to be able to send / receive data to many clients at once. I think the answer is non-blocking sockets / OOP / callback functions but I'm really not sure. Does anybody have advice for this? I would like to make it clear that I'm hoping for a pure PHP solution,

 

Thanks

 

<?php

set_time_limit(0);

$s_sock = socket_create(AF_INET, SOCK_STREAM, 0);
echo "socket created\r\n";

socket_bind($s_sock, "0.0.0.0", 4523);
echo "socket bound\r\n";

socket_listen($s_sock, 10);
echo "socket listening\r\n";

while($c_sock = socket_accept($s_sock)) {
    $usrname = '';
    echo "new connection\r\n";
    while(1) {
        $cmd = '';
        do {
        $c = socket_read($c_sock, 1024);
        $cmd.=$c;
        }while(!substr_count($cmd, "\n"));
        $cmd = str_replace("\r", '', $cmd);
        $cmd = str_replace("\n", '', $cmd);
        echo "got a command\r\n";
        $cmd = explode(' ', $cmd);
        switch($cmd[0]) {
            case 'HI':
                $usrname = $cmd[1];
                socket_write($c_sock, "hello $cmd[1]\r\n");
                break;
            case 'NOTHING':
                socket_write($c_sock, "*does nothing*\r\n");
                break;
            case 'SHUTDOWN':
                socket_write($c_sock, "shuttung down now...\r\n");
                sleep(2);
                break 3;
            case 'QUIT':
                socket_write($c_sock, "bye $usrname\r\n");
                break 2;
            default:
                socket_write($c_sock, "Invalid command : $cmd[0]\r\n");
                break;
        }
    }
    socket_close($c_sock);
}

socket_close($s_sock);

?>

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.