我正在尝试使用 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>
一切正常,唯一的问题是当我们关闭终端 Web 套接字 ID 时。