一、ws_server.php
<?php
//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
// var_dump($request->fd, $request->get, $request->server);
// var_dump($request->fd);
// $ws->push($request->fd, "hello, ZHG welcome\n");
print_r($request->fd);
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
echo "Message: {$frame->data}\n";
$ws->push($frame->fd, "push-secesss: {$frame->data}");
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();
二、可以使用 Chrome 浏览器进行测试,JS 代码为:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>swoole_webserver测试</h1>
<script>
var wsServer = 'ws://sw.dabaicai.ink:9502';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
websocket.send("hello xiaohui");
console.log("Connected -swoole-success");
};
websocket.onclose = function (evt) {
console.log("Disconnected");
};
websocket.onmessage = function (evt) {
console.log('ws-server-return-data: ' + evt.data);
};
websocket.onerror = function (evt, e) {
console.log('Error occured: ' + evt.data);
};
</script>
</body>
</html>
三、测试效果
开启了http服务来测试 WebSocket效果
44.png
网友评论