windows 搭建 swoole开发环境(官网已支持)
参考文章:https://zhuanlan.zhihu.com/p/628489045
1.下载:https://wenda-1252906962.file.myqcloud.com/dist/swoole-cli-v5.0.3-cygwin-x64.zip
2.解压后放到自己的目录:F:\work\swoole-cli-v5.0.3-cygwin-x64
3.添加系统变量:

4.编写server.php后端文件,index.html前端文件
<?php //创建WebSocket Server对象,监听0.0.0.0:9502端口。 $ws = new Swoole\WebSocket\Server('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!xw\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();
<!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>
5.CMD运行server.php,然后浏览器打开index.html。看到如下效果。


浙公网安备 33010602011771号