即使终端关闭,也要保持swoole websocket的运行

时间:2018-06-08 08:57:40

标签: php swoole

我正在尝试使用Socket创建一个聊天应用程序并使用Swoole作为后端。我成功创建了与服务器客户端的连接,但我现在面临的问题是每当我关闭终端时,WebSocket无法连接。 服务器代码: -

<?php
//Create the websocket server object 
$websocket_server = new swoole_websocket_server("MY_IP", 3000);

// Register function of the opening connection event
$websocket_server->on('open', function($websocket_server, $request){
    var_dump($request->fd, $request->get, $request->server);
    $websocket_server->push($request->fd, "Hello welcome\n");
});

// Register function of the receiving message event
$websocket_server->on('message', function($websocket_server, $frame){
    echo "Message : {$frame->data}\n";
    $websocket_server->push($frame->fd, "Server : {$frame->data}");
});

// Register function of the close event
$websocket_server->on('close', function($websocket_server, $fd){
    echo "client_{$fd} is closed\n";
});

// Start the server
$websocket_server->start();

客户端代码: -

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<script type="text/javascript">
var wsServer = 'ws://IP:3000';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
    console.log("Connected to WebSocket server.");
};

websocket.onclose = function (evt) {
    console.log("Disconnected");
};

websocket.onmessage = function (evt) {
    console.log('Retrieved data from server: ' + evt.data);
};

websocket.onerror = function (evt, e) {
    console.log('Error occured: ' + evt.data);
};
</script>
</body>
</html>

一切正常,唯一的问题是当我们关闭终端网络套接字ID时。

1 个答案:

答案 0 :(得分:0)

我在Git上得到答案。请在下面添加以下代码

$websocket_server = new swoole_websocket_server("MY_IP", 3000);
$websocket_server->set([
    'daemonize' => true,
]);