Home > Backend Development > PHP Tutorial > php怎么同时处理多个任务(关于php socket)

php怎么同时处理多个任务(关于php socket)

WBOY
Release: 2016-06-13 13:19:25
Original
913 people have browsed it

php如何同时处理多个任务(关于php socket)
我现在要写一个socket监听一个端口,如果有数据过来,开始while循环,现在问题出来了,同时只能有一个客户端连接这个服务端,有第二个连接时,就连接不上,有的朋友说就accept了一次,但是应该如何修改呢?下面贴上我的代码,请会的朋友指导下(说详细点,最好可以帮我修改下代码)



PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

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


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