第一步下载:swoole官网下载Swoole - PHP 协程框架cygwin-x64,只支持 64 位的系统;

第二步解压到指定文件夹:G:swoole-cli-v5.0.3-cygwin-x64

第三步设置环境变量:把解压后的文件夹下的 bin 目录路径配置到系统的 Path 环境变量中,确定保存


第四步检查安装情况:打开CMD命令行输入:swoole-cli -v,安装成功

第五步:编写简单的WebSocket服务器代码:sw.php
<?php
//创建WebSocket Server对象,监听0.0.0.0:9502端口。
$ws = new SwooleWebSocketServer('0.0.0.0', 9502);
//监听WebSocket连接打开事件。
$ws->on('Open', function ($ws, $request) {
echo "Message: {$request->fd} is in!n";
$ws->push($request->fd, "hello, welcome!xwn");
});
//监听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 closedn";
});
$ws->start();
第六步:编写简单的WebSocket客户端代码:index.html,客户端index使用phpstudy虚拟域名指向,配置可以在浏览器打开访问
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>swoole-cli demo</title>
</head>
<body>
<script>
var wsServer = 'ws://127.0.0.1:9502';
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>
第七步:运行服务端:swoole-cli sw.php;浏览器访问客户端index.html,完成!


