当前位置:Gxlcms > PHP教程 > phpsocket编程读完成后写堵塞

phpsocket编程读完成后写堵塞

时间:2021-07-01 10:21:17 帮助过:4人阅读

php socket编程 读完成后写阻塞
server端代码 如下:

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);


client端, 代码如下:


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);

如果将server端对client read操作换成循环内部读取,则client会一直处于 wait data状态。
有办法让server端循环读的情况下,读完后给client写数据吗



socket tcp php server

分享到:


------解决方案--------------------
你这个循环没有错,但是一次数据发送完成就关闭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

------解决方案--------------------
引用:
Quote: 引用:


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");

人气教程排行