求助 socket 同时只能有一个客户端连接一个端口并往上面发送数据
同时只能有一个客户端连接一个端口(如8090)并往上面发送数据,当有第二个客户端连接时这个8090端口时 就连接不上了
有的朋友说服务端就accept一次,那如何accept多次啊!下面贴上我的代码
$commonprotocol = getprotobyname(tcp);
$socket = socket_create(af_inet, sock_stream, $commonprotocol);
@socket_bind($socket, '192.168.1.202', 8888);
@socket_listen($socket);
// initialize the buffer
$buffer = no data;
while(true)
{
sleep(1);
// accept any connections coming in on this socket
$connection = @socket_accept($socket);
printf(socket connected\r\n);
// check to see if there is anything in the buffer
if($buffer != )
{
printf(something is in the buffer...sending data...\r\n);
@socket_write($connection, $buffer . \r\n);
printf(wrote to socket\r\n);
}
else
{
printf(no data in the buffer\r\n);
}
// get the input
while($data = @socket_read($connection, 14, php_normal_read))
{
if (!empty($data)){
$buffer = $data;
//文件驱动模式
/*$f = fopen(dirname(__file__).'/file/'.date('ymdhis').'.txt','w');
fwrite($f,$buffer);
fclose($f); */
socket_set_nonblock($connection);
socket_getpeername($connection,&$remoteip,&$remoteport);
echo $remoteip.\r\n;
echo $remoteport.\r\n;
$data=str_split($buffer);
print_r($data);
foreach($data as $v){
echo dechex(ord($v)).\t;
}
echo \r\n;
}
}
@socket_close($connection);
printf(closed the socket\r\n\r\n);
}
------解决方案--------------------
用非阻塞模式,具体百度