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

发布时间 2023-10-24 16:36:28作者: kevin_yang123

官方下载地址:

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

<?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,完成!