php如何同時處理多個任務(關於php socket)
我現在要寫一個socket監聽一個連接埠,如果有資料過來,開始while迴圈,現在問題出來了,同時只能有一個用戶端串連這個服務端,有第二個串連時,就串連不上,有的朋友說就accept了一次,但是應該如何修改呢?下面貼上My Code,請會的朋友指導下(說詳細點,最好可以幫我修改下代碼)
PHP code
$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"); }
------解決方案--------------------
非阻塞模式