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。看到如下效果。

 

posted @   流浪2024  阅读(351)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2021-06-04 反向代理和正向代理区别
点击右上角即可分享
微信分享提示