服务器端:
1 //创建服务器端 2 $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); 3 4 //设置配置 - 设置套流的最大超时时间1秒 5 socket_set_option($socket,SOL_SOCKET, SO_RCVTIMEO, array('sec'=>1, 'usec'=>0)); 6 socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec'=>6, 'usec'=>0)); 7 $host_ip = 'localhost'; 8 $host_port = '83'; 9 //连接服务器套件 10 if(socket_connect($socket, $host_ip, $host_port) == false){ 11 echo 'service bind fail:'.socket_strerror(socket_last_error()); 12 }else{ 13 //发送命令 14 $in = "HEAD / HTTP/1.1 "; 15 $in .= "Connection: Close "; 16 $out = ''; 17 echo "Send Command.........."; 18 $in = "sun "; 19 socket_write($socket, $in, strlen($in)); 20 echo "OK. "; 21 echo "Reading Backinformatin: "; 22 while ($out = socket_read($socket, 2048)) { 23 echo $out; 24 } 25 echo "Close socket........"; 26 socket_close($socket); 27 echo "OK,He He. "; 28 29 }
客户端:
1 //创建服务器端 2 $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); 3 $host_ip = 'localhost'; 4 $host_port = '83'; 5 //绑定接收主机与端口 6 if(socket_bind($socket,$host_ip,$host_port) == false){ 7 echo 'service bind fail:'.socket_strerror(socket_last_error()); 8 } 9 //监听套件流 10 if(socket_listen($socket, 4) == false){ 11 echo 'service listen fail:'.socket_strerror(socket_last_error()); 12 } 13 //接收命令 14 if (($msgsock = @socket_accept($socket)) < 0) { 15 echo "命令接收失败原因: " . socket_strerror($msgsock) . " "; 16 } 17 $msg = " PHP Test Server. " ."用quit,shutdown,sun...等命令测试. "; 18 $msg = mb_check_encoding($msg,'GBK','utf-8'); 19 20 socket_write($msgsock, $msg, strlen($msg)); 21 22 23 if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) { 24 echo "socket_read() failed: reason: " . socket_strerror($ret) . " "; 25 } 26 // if (!$buf = trim($buf)) { 27 // continue; 28 // } 29 if ($buf == 'quit') { 30 exit(); 31 } 32 if ($buf == 'shutdown') { 33 socket_close($msgsock); 34 } 35 if ($buf == 'sun') { 36 echo'what are you doing?'; 37 } 38 $talkback = "Backinformation : '$buf'. "; 39 socket_write($msgsock, $talkback, strlen($talkback)); 40 echo "$buf "; 41 42 socket_close($socket);