这篇文章将为大家详细讲解有关怎么用PHP中socket实现客户端到服务端的通信,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
一、server.php服务端:
<?php error_reporting(E_ALL); set_time_limit(0); ob_implicit_flush(); //本地IP $address = 'localhost'; //设置用111端口进行通信 $port = 111; //创建SOCKET if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) { echo "socket创建失败原因 " . socket_strerror($sock) . "\n"; } if (($ret = socket_bind($sock, $address, $port)) < 0) { echo "创建套接字失败原因 " . socket_strerror($ret) . "\n"; } //监听 if (($ret = socket_listen($sock, 5)) < 0) { echo "监听失败原因 " . socket_strerror($ret) . "\n"; } do { //接收命令 if (($msgsock = @socket_accept($sock)) < 0) { echo "命令接收失败原因: " . socket_strerror($msgsock) . "\n"; break; } $msg = "\nPHP Test Server. \n" ."用quit,shutdown,sun...等命令测试.\n"; @socket_write($msgsock, $msg, strlen($msg)); do { if (false === ($buf = @socket_read($msgsock, 2048, PHP_NORMAL_READ))) { echo "socket_read() failed: reason: " . socket_strerror($ret) . "\n"; break 2; } if (!$buf = trim($buf)) { continue; } if ($buf == 'quit') { break; } if ($buf == 'shutdown') { socket_close($msgsock); break 2; } if ($buf == 'sun') { echo'what are you doing?'; } $talkback = "Backinformation : '$buf'.\n"; socket_write($msgsock, $talkback, strlen($talkback)); echo "$buf\n"; } while (true); socket_close($msgsock); } while (true); socket_close($sock); ?>
二、client.php客户端:
<?php error_reporting(E_ALL); //端口111 $service_port = 111; //本地 $address = 'localhost'; //创建 TCP/IP socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket < 0) { echo "socket创建失败原因: " . socket_strerror($socket) . "\n"; } else { echo "OK,HE HE.\n"; } $result = socket_connect($socket, $address, $service_port); if ($result < 0) { echo "SOCKET连接失败原因: ($result) " . socket_strerror($result) . "\n"; } else { echo "OK.\n"; } //发送命令 $in = "HEAD / HTTP/1.1\r\n"; $in .= "Connection: Close\r\n\r\n"; $out = ''; echo "Send Command.........."; $in = "sun\n"; socket_write($socket, $in, strlen($in)); echo "OK.\n"; echo "Reading Backinformatin:\n\n"; while ($out = socket_read($socket, 2048)) { echo $out; } echo "Close socket........"; socket_close($socket); echo "OK,He He.\n\n"; ?>
这两段代码是简单介绍用PHP实现客户端和服务端的通信
具体操作,在DOS下用PHP命令打开SERVER,处于监听状态..
再打开一个DOS窗口,用PHP命令打开CLIENT,会得到服务端的回应....
关于“怎么用PHP中socket实现客户端到服务端的通信”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。