TheEvilMonkeyMan Posted July 12, 2008 Share Posted July 12, 2008 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); ?> Quote Link to comment Share on other sites More sharing options...
ratcateme Posted July 12, 2008 Share Posted July 12, 2008 read this the second block of code looks like want you want. Scott. Quote Link to comment Share on other sites More sharing options...
TheEvilMonkeyMan Posted July 12, 2008 Author Share Posted July 12, 2008 That code shows me exactly what I need to know, thanks alot Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.