Home > Backend Development > PHP Tutorial > socket 同时只能有一个客户端连接一个端口并往上面发送数据

socket 同时只能有一个客户端连接一个端口并往上面发送数据

WBOY
Release: 2016-06-13 12:50:56
Original
1529 people have browsed it

求助 socket 同时只能有一个客户端连接一个端口并往上面发送数据
同时只能有一个客户端连接一个端口(如8090)并往上面发送数据,当有第二个客户端连接时这个8090端口时 就连接不上了
有的朋友说服务端就accept一次,那如何accept多次啊!下面贴上我的代码

$commonProtocol = getprotobyname("tcp");<br />
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);<br />
@socket_bind($socket, '192.168.1.202', 8888);<br />
@socket_listen($socket);<br />
// Initialize the buffer<br />
$buffer = "NO DATA";<br />
<br />
<br />
while(true)<br />
{<br />
sleep(1);    <br />
 // Accept any connections coming in on this socket<br />
<br />
 $connection = @socket_accept($socket);<br />
 printf("Socket connected\r\n");<br />
 // Check to see if there is anything in the buffer<br />
 if($buffer != "")<br />
 {<br />
  printf("Something is in the buffer...sending data...\r\n");<br />
  @socket_write($connection, $buffer . "\r\n");<br />
  printf("Wrote to socket\r\n");<br />
 }<br />
 else<br />
 {<br />
  printf("No Data in the buffer\r\n");<br />
 }<br />
 // Get the input<br />
 while($data = @socket_read($connection, 14, PHP_NORMAL_READ))<br />
 {<br />
     <br />
     if (!empty($data)){<br />
         $buffer = $data;  <br />
<br />
 //文件驱动模式 <br />
      /*$f = fopen(dirname(__FILE__).'/file/'.date('YmdHis').'.txt','w');<br />
    fwrite($f,$buffer); <br />
    fclose($f); */ <br />
 <br />
   socket_set_nonblock($connection);<br />
   socket_getpeername($connection,&$remoteIP,&$remotePort);<br />
echo $remoteIP."\r\n";<br />
echo $remotePort."\r\n";<br />
 <br />
 <br />
 <br />
 $data=str_split($buffer);<br />
 <br />
 print_r($data);<br />
 <br />
 foreach($data as $v){<br />
     echo dechex(ord($v))."\t";<br />
     }<br />
 echo "\r\n";<br />
 <br />
     }<br />
  <br />
<br />
<br />
  <br />
 }<br />
 @socket_close($connection);<br />
 printf("Closed the socket\r\n\r\n");<br />
 <br />
 <br />
}<br />
<br />
<br />
<br />
Copy after login

------解决方案--------------------
用非阻塞模式,具体百度

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template