1、服务器监听
1 error_reporting(E_ALL); 2 //端口111 3 $service_port = 1234; 4 //本地 5 $address = '192.168.0.103'; 6 //创建 TCP/IP socket 7 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); 8 echo $socket; 9 var_dump($socket); 10 if ($socket < 0) 11 { 12 echo "socket创建失败原因: " . socket_strerror($socket) . " "; 13 } 14 else 15 { 16 echo "OK,HE HE. "; 17 } 18 $result = socket_connect($socket, $address, $service_port); 19 if ($result) 20 { 21 echo "OK. "; 22 } 23 else 24 { 25 echo "SOCKET连接失败原因: ($result) " . socket_strerror($result) . " "; 26 } 27 28 //发送命令 29 $in = "HEAD / HTTP/1.1 "; 30 $in .= "Connection: Close "; 31 $out = ''; 32 echo "Send Command.........."; 33 $in = "sun "; 34 socket_write($socket, $in, strlen($in)); 35 echo "OK. "; 36 echo "Reading Backinformatin: "; 37 while ($out = socket_read($socket, 2048)) { 38 echo $out; 39 } 40 echo "Close socket........"; 41 socket_close($socket);
2、客户端访问
1 $attr = array("id"=>"admin","pw"=>"admin","mark"=>"1"); 2 $json = json_encode($attr); 3 set_time_limit(0); 4 //192.168.247.1 5 $host = "192.168.0.103"; 6 $port = 12345; 7 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)or die("Could not create socket "); // 创建一个Socket 8 $user = "admin"; 9 $connection = socket_connect($socket, $host, $port) or die("Could not connet server "); // 连接 10 socket_write($socket, $json) or die("Write failed "); // 数据传送 向服务器发送消息 11 while ($buff = @socket_read($socket, 1024, PHP_NORMAL_READ)) { 12 echo("Response was:" . $buff . " "); 13 } 14 socket_close($socket);