常有人困惑php的socket服务,现在有libevent和多线程了,但是我还是整一个select的
<?php $addr = '0.0.0.0'; $port = 1234; $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) { echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL; } if($socket < 0) { echo "Socket create:".$socket_strerror($socket)." "; exit; } if (! ($ret = socket_bind($socket, $addr, $port)) ) { $cmd =isset($_SERVER['WINDIR'])? "netstat -an -o | find "".$port.""":"netstat -anp | grep "".$port."""; $output = NULL; exec( $cmd, $output , $return_var); echo " ----------------------------------------------- $cmd <pre>"; var_dump($output, $return_var); echo "/<pre>"; //echo "//AS! "; exit; } if ( ($ret = socket_listen($socket, 5)) < 0 ) { echo "socket listen:".socket_strerror()." "; exit; } socket_set_nonblock($socket); $clients = array($socket); while(true) { $read = $clients; $writes=NULL;$execs=NULL; if(socket_select($read, $writes, $execs, 2) < 1){ echo "."; continue; } if(in_array($socket,$read)) { $newsock = socket_accept($socket); socket_set_nonblock($newsock); socket_getpeername($newsock,$remoteIP,$remotePort); $userSN = $remoteIP.'_'.$remotePort; echo $userSN.' connetect in'.chr(10); $clients[$userSN] = $newsock; socket_write($newsock,'welcome '.$userSN.chr(10)); continue; } foreach($read as $read_sock) { $data = @socket_read($read_sock, 2048, PHP_BINARY_READ); $data = trim($data); if(strlen($data) == 2048){ socket_close($read_sock); continue; } @socket_getpeername($read_sock, $remoteIP, $remotePort); $userSN = $remoteIP.'_'.$remotePort; echo $userSN.' say:'.$data.chr(10); socket_write($read_sock,'you say:'.$data); } }
php s1.php
telnet 127.0.0.1 1234
telnet 127.0.0.1 1234