当前位置:Gxlcms > PHP教程 > socket同时只能有一个客户端连接一个端口并往下面发送数据

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

时间:2021-07-01 10:21:17 帮助过:78人阅读

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

PHP code
  1. <!--
  2. Code highlighting produced by Actipro CodeHighlighter (freeware)
  3. http://www.CodeHighlighter.com/
  4. -->$commonProtocol = getprotobyname("tcp");
  5. $socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol);
  6. @socket_bind($socket, '192.168.1.202', 8888);
  7. @socket_listen($socket);
  8. // Initialize the buffer
  9. $buffer = "NO DATA";
  10. while(true)
  11. {
  12. sleep(1);
  13. // Accept any connections coming in on this socket
  14. $connection = @socket_accept($socket);
  15. printf("Socket connected\r\n");
  16. // Check to see if there is anything in the buffer
  17. if($buffer != "")
  18. {
  19. printf("Something is in the buffer...sending data...\r\n");
  20. @socket_write($connection, $buffer . "\r\n");
  21. printf("Wrote to socket\r\n");
  22. }
  23. else
  24. {
  25. printf("No Data in the buffer\r\n");
  26. }
  27. // Get the input
  28. while($data = @socket_read($connection, 14, PHP_NORMAL_READ))
  29. {
  30. if (!empty($data)){
  31. $buffer = $data;
  32. //文件驱动模式
  33. /*$f = fopen(dirname(__FILE__).'/file/'.date('YmdHis').'.txt','w');
  34. fwrite($f,$buffer);
  35. fclose($f); */
  36. socket_set_nonblock($connection);
  37. socket_getpeername($connection,&$remoteIP,&$remotePort);
  38. echo $remoteIP."\r\n";
  39. echo $remotePort."\r\n";
  40. $data=str_split($buffer);
  41. print_r($data);
  42. foreach($data as $v){
  43. echo dechex(ord($v))."\t";
  44. }
  45. echo "\r\n";
  46. }
  47. }
  48. @socket_close($connection);
  49. printf("Closed the socket\r\n\r\n");
  50. }


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

人气教程排行