1.在/web/tool/demo/server下新建ws_server.php
```
<?php
$server = new swoole_websocket_server("0.0.0.0", 9501);
$server->set(
[
'enable_static_handler' => true,
'document_root' => "/web/tool/demo/server",
]
);
//监听websocket连接打开事件
$server->on('open', 'onOpen');
function onOpen($server, $request) {
print_r($request->fd);
}
// 监听ws消息事件
$server->on('message', function (swoole_websocket_server $server, $frame) {
echo "接收 from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
$server->push($frame->fd, "singwa-push-secesss");//向客户端推送数据
});
$server->on('close', function ($ser, $fd) {
echo "client {$fd} 关闭\n";
});
$server->start();
```
2.新建/web/tool/demo/html/ws_client.html
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>singwa-swoole-ws测试<h1>
<script>
var wsUrl = "ws://xxxxxx.com:9501";
var websocket = new WebSocket(wsUrl);
//实例对象的onopen属性
websocket.onopen = function(evt) {
websocket.send("hello");//向服务器发送数据,服务器才有回调
console.log("conected-swoole-success");
}
// 实例化 onmessage
websocket.onmessage = function(evt) {
console.log("ws-server-return-data:" + evt.data);
}
//onclose
websocket.onclose = function(evt) {
console.log("close");
}
//onerror
websocket.onerror = function(evt, e) {
console.log("error:" + evt.data);
}
</script>
</body>
</html>
```
3.测试
![](https://img.kancloud.cn/79/75/79755642f80ad308172b679cc1d75051_1326x466.png)
![](https://img.kancloud.cn/9b/82/9b82cbb2c1fb45327317dc686d8541ee_661x131.png)