php Socket通信
1 <?php 2 error_reporting(0); 3 $host = "0.0.0.0"; 4 $port = 1082; 5 $maxUser = 10; 6 7 set_time_limit(0); 8 9 10 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket create failed: " . socket_strerror( socket_last_error() ) . "\n"); 11 12 socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, true) or die("option set failed: " . socket_strerror( socket_last_error() ) . "\n"); 13 socket_bind($socket, $host, $port) or die("socket_bind() failed: " . socket_strerror( socket_last_error() ) . "\n"); 14 socket_listen( $socket, 3 ) or die("socket_listen() failed: " . socket_strerror( socket_last_error() ) . "\n"); 15 16 echo "Starting Listen!\n"; 17 do{ 18 if( $msgSocket = socket_accept($socket) === false ){ 19 echo "socket_accept() failed: " . socket_strerror( socket_last_error() ) . "\n"; 20 break; 21 }else{ 22 $msg = "hello world"; 23 socket_write($msgSocket, $msg, strlen( $msg )); 24 25 echo "read client message\n"; 26 $buf = socket_read($msgSocket, 8192); 27 $talkback = "received message: $buf\n"; 28 29 echo $talkback; 30 31 if( false === socket_write($msgSocket, $talkback, strlen($talkback)) ){ 32 echo "socket_write() failed reason:" . socket_strerror(socket_last_error($sock)) ."\n"; 33 }else{ 34 echo "send success\n"; 35 } 36 37 //socket_send($msgSocket, $buf, $len, $flags); 38 } 39 socket_close( $msgSocket ); 40 41 }while ( true ); 42 43 socket_close($socket); 44 ?>