php select socket

因为客户端是长连接,如果客户端非正常断开,服务端会在socket_accept阻塞,现在使用select非阻塞模式socket,读取客户端信息。

 1 <?php 
 2 date_default_timezone_set("Asia/Shanghai");
 3 include_once "Db.php";
 4 $sfd = socket_create(AF_INET, SOCK_STREAM, 0); 
 5 socket_bind($sfd, "192.168.191.1", 9001); 
 6 socket_listen($sfd, 10); //监听10个
 7 socket_set_option($sfd, SOL_SOCKET, SO_REUSEADDR, 1); //重用端口
 8 socket_set_nonblock($sfd); //非阻塞
 9 $rfds = array($sfd); 
10 $wfds = array(); 
11 do{ 
12     $rs = $rfds;  
13     $ws = $wfds; 
14     $es = array(); 
15     $ret = socket_select($rs, $ws, $es, 3); 
16     //read event 
17     foreach($rs as $fd){
18             
19         if($fd == $sfd){ 
20             $cfd = socket_accept($sfd); 
21             socket_set_nonblock($cfd); 
22             $rfds[] = $cfd; 
23             echo "new client coming, fd=$cfd\n"; 
24         }else{
25             //获取客户端IP地址
26             socket_getpeername($fd, $addr, $port);
27             //读取客户端信息
28             $msg = socket_read($fd, 1024); 
29             echo date("H:i:s")." $fd $msg";
30             $arr=explode(",", $msg);
31             //更新到数据库 
32             $sql = "update test set wendu = $arr[0],shidu = $arr[1], green = $arr[2],yellow=$arr[3] ,red=$arr[4],dianliu=$arr[5],
             dianya=$arr[6] where ip = '$addr'" ; 33 Db::query($sql); 34 } 35 } 36 37 38 }while(true);

 

posted @ 2017-02-23 08:48  zbchls  阅读(4088)  评论(0编辑  收藏  举报