服务器端环境
系统环境
uUbuntu 20.04
php版本
PHP 7.4.3
服务文件 ws_server.php
<?php
//创建WebSocket Server对象,监听0.0.0.0:9501端口
$ws = new Swoole\WebSocket\Server(‘0.0.0.0‘, 9501);
//监听WebSocket连接打开事件
$ws->on(‘Open‘, function ($ws, $request) {
$ws->push($request->fd, "hello, websocket\n");
});
//监听WebSocket消息事件
$ws->on(‘Message‘, function ($ws, $frame) {
echo "Message: {$frame->data}\n";
$ws->push($frame->fd, "server: {$frame->data}");
});
//监听WebSocket连接关闭事件
$ws->on(‘Close‘, function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();
启动服务
php ws_server.php
测试
测试文件
vi web_socket.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket测试</title>
<script>
function initWebSocket(wsUri) {
var websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) {
console.log(‘连接建立中... ‘+wsUri);
};
websocket.onclose = function(evt) {
console.log(‘连接关闭中...‘, evt);
};
websocket.onmessage = function(evt) {
console.log(‘收到来自服务端的消息:‘, evt.data);
};
websocket.onerror = function(evt) {
console.log(‘发生错误...‘, evt);
};
return websocket;
}
var websocket = initWebSocket("ws://118.195.173.53:9501");
var msg, i = 0;
var loop = setInterval(function(){
msg = "Hello " + (i++);
if(websocket.readyState == WebSocket.OPEN) {
websocket.send(msg);
console.log(‘已发送消息:‘ + msg);
} else {
clearInterval(loop);
console.log(‘连接已关闭,拜拜~‘);
}
}, 3000);
</script>
</head>
<body>
请按 F12 打开控制台查看消息
</body>
</html>
浏览器web_socket.html
请按 F12 打开控制台查看消息
注意事项:
1 检测防火墙是否放开9501端口
2 云服务器要开发9501端口
3 server.php监听的IP 0.0.0.0