时间:2021-07-01 10:21:17 帮助过:4人阅读
set_time_limit(0);
$host = "127.0.0.1";
$port = 12345;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n"); // 创建一个Socket
$result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n"); //绑定Socket到端口
$result = socket_listen($socket) or die("Could not set up socket listener\n"); // 开始监听连接
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // 处理通信
//若换成循环接收数据,客户端将一直处理等待接收状态
$input = socket_read($spawn, 1024) or die("Could not read data\n");
/*
while (( $data = socket_read($spawn, 1024)) != false)
$input .= $data;
*/
echo 'input:', strlen($input), "\n";
$output = date("Y-m-d H:i:s"). "\n"; //处理客户端输入并返回结果
echo "output:", $output, "\n";
// 数据传送 向客户端写入返回结果
socket_write($spawn, $output, strlen($output)) or die("Could not write output\n");
// 关闭sockets
socket_close($spawn);
socket_close($socket);
set_time_limit(0);
$host = "127.0.0.1";
$port = 12345;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)or die("Could not create socket\n"); // 创建一个Socket
$connection = socket_connect($socket, $host, $port) or die("Could not connet server\n"); // 连接
socket_write($socket, "time") or die("Write failed\n"); // 数据传送 向服务器发送消息
echo 'wait for data';
while (($buffer = socket_read($socket, 1024))!=false) {
echo("Data sent was: time\nResponse was:" . $buffer . "\n");
}
socket_close($socket);
while (true) {
$msg = socket_accept ($socket); // 接受一个SOCKET
if (!$msg) {
echo "socket_accept() failed:".socket_strerror ($msg)."\n";
break;
}
while (true) {
$command = strtoupper (trim (socket_read ($msg, 1024))); //等待客户端数据
if (!$command) break;
//相关处理,比如直接回显
socket_write ($msg, $command, strlen ($command));
}
socket_close ($msg);
if ($command == "QUIT") //如果收到的是通讯结束
break;
}
socket_close ($socket); // 关闭SOCKET