• 技术文章 >后端开发 >php教程

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

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

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


    ------解决方案--------------------
    用非阻塞模式,具体百度
    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    上一篇: php中require跟include的几点区别 下一篇: thinkphp判断是不是有数据
    VIP课程(WEB全栈开发)

    相关文章推荐

    • 【腾讯云】年中优惠,「专享618元」优惠券!• PHP面试之常见基础算法(附代码示例)• Zend Framework入门知识点小结_php实例• Zend Framework+smarty用法实例详解_php实例• 基于php实现七牛抓取远程图片_php实例• php语言中使用json的技巧及json的实现代码详解_php实例
    1/1

    PHP中文网