随笔 - 337  文章 - 5  评论 - 3  阅读 - 39万

windows 搭建 swoole开发环境(官网已支持)

官方下载地址:

https://www.swoole.com/

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

 

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

我的电脑。属性-》高级系统设置-》环境变量-》

 添加配置路径为D:\swoole\swoole-cli-v5.0.3-cygwin-x64\bin ,安装文件包目录下的bin

第四个:编写简单的WebSocket服务器代码:sw.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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();

 第五步:编写简单的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,完成!

 

 

posted on   kevin_yang123  阅读(338)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示