首页  >  文章  >  后端开发  >  php socket编程 读完成后写堵塞

php socket编程 读完成后写堵塞

WBOY
WBOY原创
2016-06-13 12:34:461134浏览

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

<br />
<?php<br />
set_time_limit(0);<br />
 <br />
$host = "127.0.0.1";<br />
$port = 12345;<br />
 <br />
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create	socket\n"); // 创建一个Socket<br />
 <br />
$result = socket_bind($socket, $host, $port) or die("Could not bind tosocket\n"); //绑定Socket到端口<br />
 <br />
$result = socket_listen($socket) or die("Could not set up socket listener\n"); // 开始监听连接<br />
 <br />
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // 处理通信<br />
<br />
//若换成循环接收数据,客户端将一直处理等待接收状态<br />
$input = socket_read($spawn, 1024) or die("Could not read data\n");<br />
/* <br />
while (( $data = socket_read($spawn, 1024)) != false) <br />
	$input .= $data;<br />
*/ <br />
<br />
echo 'input:', strlen($input), "\n";<br />
 <br />
$output = date("Y-m-d H:i:s"). "\n"; //处理客户端输入并返回结果<br />
 <br />
echo "output:", $output, "\n";<br />
 <br />
//	数据传送 向客户端写入返回结果<br />
socket_write($spawn, $output, strlen($output)) or die("Could not write output\n");	<br />
 <br />
// 关闭sockets<br />
socket_close($spawn);<br />
socket_close($socket);


client端, 代码如下:
<br />
<?php<br />
<br />
set_time_limit(0);<br />
 <br />
$host = "127.0.0.1";<br />
$port = 12345;<br />
 <br />
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)or die("Could not create	socket\n"); // 创建一个Socket<br />
 <br />
$connection = socket_connect($socket, $host, $port) or die("Could not connet server\n");    //  连接<br />
 <br />
socket_write($socket, "time") or die("Write failed\n"); // 数据传送 向服务器发送消息<br />
<br />
echo 'wait for data';<br />
<br />
while (($buffer = socket_read($socket, 1024))!=false) {<br />
    echo("Data sent was: time\nResponse was:" . $buffer . "\n");<br />
}<br />
 <br />
socket_close($socket);<br />

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



socket tcp php server
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn