//server.php <? // 设置一些基本的变量 $host = "localhost"; $port = 1111; // 设置超时时间 set_time_limit(0); // 创建一个Socket $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n"); //绑定Socket到端口 $result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n"); // 开始监听链接 $result = socket_listen($socket, 3) or die("Could not set up socket listener\n"); // accept incoming connections file_put_contents("../log/server.log", "测试连接1\r\n", FILE_APPEND); for ($i = 0; $i < 3; $i++){ // 另一个Socket来处理通信 $spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // 获得客户端的输入 $input = socket_read($spawn, 1024) or die("Could not read input\n"); file_put_contents("../log/server.log", "2 客户端发的数据是".$input."\r\n", FILE_APPEND); // 向客户端发送数据 $input = trim($input); //处理客户端输入并返回结果 $output = strrev($input)."\n"; socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n"); } file_put_contents("../log/server.log", "测试连接3\r\n", FILE_APPEND); // 关闭sockets socket_close($spawn); socket_close($socket);
//client.php <?php $port = 1111; $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_connect($sock, '127.0.0.1', $port); $line = "heihei"; socket_write ($sock, $line, strlen ($line)); $input = socket_read($sock, 1024) or die("Could not read input\n"); file_put_contents("../log/server.log", "服务器发来的数据是".$input."\r\n", FILE_APPEND); echo "服务器发来的数据是".$input; socket_close($sock);