dongxun6458 2014-02-24 18:32
浏览 51
已采纳

让PHP服务器脚本持久监听套接字是否阻塞?

I am writing a project that is in 2 parts.

So far I have a front end View.php (HTML5,CSS3,JQuery) and this will query the server.php

The server PHP opens a TCP socket to a server and listens in and can make commands by writing to the socket.

The normal procedure now goes like this

View.php -> Calls using rest API to server.php
Server.php -> Connects to TCP -> Reads from TCP -> Json_encodes & print -> close TCP socket connection.

What I want to achieve is a script Server.php that once started. It constantly listens in to a server, until it gets a shutdown command. I want to keep a fsocket connection open. Any thoughts?

  • 写回答

1条回答

  • dt102282 2016-07-26 20:33
    关注

    The answer is using non blocking programming. In PHP we have specific function for non blocking I/O. For sockets you should use socket_set_nonblock function on a socket resource.

    $port = 8081;
    $address = '127.0.0.1';
    
    if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
        echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "
    ";
        exit();
    }
    if (socket_bind($sock, $address, $port) === false) {
        echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "
    ";
        exit();
    }
    if (socket_listen($sock, 5) === false) {
        echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "
    ";
    }
    socket_set_nonblock($sock);
    echo "listening for new connection".PHP_EOL;
    $conneted_clients = [];
    
    do {
       $clientsock = socket_accept($sock);
       if($clientsock !== false){
    
            socket_set_nonblock($clientsock);
            $conneted_clients[] = $clientsock;
            socket_getpeername($clientsock,$address);
            echo "New Connection from: ".$address.PHP_EOL;
    
            $msg = PHP_EOL."Welcome to the PHP Test Server. " . PHP_EOL.
            "To quit, type 'quit'. To shut down the server type 'shutdown'." . PHP_EOL;
    
            socket_write($clientsock, $msg, strlen($msg));
        }
        $status = check_clients($conneted_clients);
    
        if(!$status) break;
        usleep(500000);
    } while (true);
    
    function check_clients($clients)
    {
        foreach($clients as $key => $con)
        {
            if(get_resource_type($con) !== "Socket")
            {   
                socket_getpeername($clientsock,$address);
                echo $address." has diconnected.".PHP_EOL;
                unset($clients[$key]);
                continue;
            }
            if (false === $buff = socket_read($con, 2048)) {
                continue;
            }
    
            $buff = trim($buff);
    
            if ($buff == 'quit') {
                socket_close($con);
                unset($clients[$key]);
                continue;
            }
            if (trim($buff) == 'shutdown') {
                socket_close($con);
                echo "shutdown initiated".PHP_EOL;
                return FALSE;
            }
            if($buff != false || $buff != null)
            {
                $talkback = "PHP: You said '$buff'.".PHP_EOL;
                socket_write($con, $talkback, strlen($talkback));
                echo "$buff".PHP_EOL;
            }
        }
        return TRUE;
    }
    echo "Closing Server";
    socket_close($sock);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。