当客户端连接到服务器时,PHP套接字服务器关闭


PHP socket server closes when connect client to server

我正在编写一个php套接字服务器脚本,它在ubuntu上运行。

它工作良好,客户端可以连接/断开到此服务器。但是,当客户端连接到该服务器时,如果该服务器长时间没有任何客户端连接,则该服务器将静默关闭。

我将超时设置为0(无限制),但服务器正在停止,没有任何错误或消息…这样的。

root@exfl:/home/projectap/sec/server_core# php socket_server.php
[exfl.kr] Starting AbsolutePitch socket server...
[2014.06.21 16:50:58] Server is listening. PID: 6442
[2014.06.21 17:28:48] Client [192.168.0.1:8795] connected to the server.
root@exfl:/home/projectap/sec/server_core#

我为这个服务器编写了如下代码。

<?php
set_time_limit(0);
error_reporting(E_ALL);
ini_set("memory_limit","2048M");
ini_set("max_execution_time", "0");
if(posix_getpid() == true) { 
    echo "[exfl.kr] Starting AbsolutePitch socket server...'n"; 
} else {
    echo getTimeToStr()."Server is already running.'n"; 
}
$cSock = array();
$socketsInformation = array();
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$bind = socket_bind($socket, "0.0.0.0", "24180");
$listen = socket_listen($socket, 5);
echo getTimeToStr()."Server is listening. PID: ".posix_getpid()."'n"; 
while(true) {
    $sockArr = array_merge(array($socket), $cSock);
    if(socket_select($sockArr, $tWrite = null, $tExcept = null, null) > 0) {
        foreach($sockArr as $sock){
            if($sock == $socket){
                $tSock = socket_accept($socket);
                socket_getpeername($tSock, $sockIp, $sockPort);
                array_push($cSock, $tSock);
                array_push($socketsInformation, array("SOCKETINDEX"=>(count($cSock)-1), "IP"=>$sockIp, "USERID"=>"", "STATUS"=>"", "AUTH"=>false));
                echo getTimeToStr()."Client [".$sockIp.":".$sockPort."] connected to the server.'n";
            } else {
                ...
            }
        }
    }
}
echo getTimeToStr()."Server closed.'n";
...
?>

当服务器突然停止时,它没有输出"服务器关闭"消息。

请帮助。

对不起,我的英语不好。

您可以尝试SO_KEEPALIVE与socket_set_options()。要了解有关选项的更多信息,请使用socket_get_options页面:

https://www.php.net/manual/en/function.socket-get-option.php

要了解更多关于socket_set_options()的用法,请使用:

https://www.php.net/manual/en/function.socket-set-option.php