环境:
ubontu14.04(部署在阿里云)
swoole
1、准备:
因为swoole的websocket使用的是9502端口,前提必须保证这些端口都可正常使用,<strong>可以让防火墙运行9502端口访问或者关闭防火墙,另一方面需要在阿里云上配置9502的安全组规则,如下所示</strong>
2、开启服务,
在cli(命令行)中运行 php server.php
server.php
<?php
$ws = new swoole_websocket_server("0.0.0.0", 9502);
$ws->set(array(
'daemonize' => true,
));
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
var_dump($request->fd, $request->get, $request->server);
$ws->push($request->fd, "hello, welcome\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();
3、客户端运行html文件
test.html
<html>
<script>
var wsServer = 'ws://47.94.15.218:9502';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
alert("Connected to WebSocket server.");
};
websocket.onclose = function (evt) {
alert("Disconnected");
};
websocket.onmessage = function (evt) {
alert('Retrieved data from server: ' + evt.data);
};
websocket.onerror = function (evt, e) {
alert('Error occured: ' + evt.data);
};
</script>
</html>
显示连接成功,如下所示
4、查看当前连接数
可运行 lsof -i:9502 进行查看
如上所示,表示当前有5个正在连接