• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

在-Swoole-中使用-WebSocket-服务端和客户端

php 搞代码 4年前 (2022-03-01) 24次浏览 已收录 0个评论

编写前端及服务器端代码

创立一个前端页面,连贯到本地的WebSocket服务器:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>WebSocket</title>
    </head>
    <body>
        <input id="sendTxt" type="text">
        <button id="sendBtn">发送</button>
        <div id="recv"></div>
    </body>
    <script type="text/javascript">
        var wsServer = 'ws://127.0.0.1:8081';
        var websocket = new WebSocket(wsServer);

        websocket.onopen = function (evt) {
            console.log("Connected to WebSocket server.");
            document.getElementById("recv").innerHTML = "Connected to WebSocket server.";
        };

        websocket.onclose = function (evt) {
            console.log("Disconnected to WebSocket server.");
        };

        websocket.onmessage = function (evt) {
            console.log('Retrieved data from server: ' + evt.data);
            document.getElementById("recv").innerHTML = 'Retrieved data from server: ' + evt.data;
        };

        websocket.onerror = function (evt, e) {
            console.log('Error occured: ' + evt.data);
            document.getElementById("recv").innerHTML = 'Error occured: ' + evt.data;
        };

        document.getElementById("sendBtn").onclick = function() {
            var txt = document.getElementById("sendTxt").value;
            websocket.send(txt);
    }
    </script>
</html>

创立一个HTTP服务器文件,用来接管前端的页面申请:

#!/usr/bin/env php
<?php

declare(strict_types=1);

$http = new Swoole\Http\Server("0.0.0.0", 80);
$http->on(
    "request",
    function (Swoole\Http\Request $request, Swoole\Http\Response $response) {
        $response->end(
            file_get_contents("./index.html")
        );
    }
);
$http->start();

创立一个WebSocket服务器文件,用来解决前端的WebSocket申请:

#!/usr/bin/env php
<?php

declare(strict_types=1);

echo "running...\n";

//创立WebSocket Server对象,监听0.0.0.0:8081端口
$ws = new Swoole\WebSocket\Server('0.0.0.0', 8081);

$ws->on('open', function (Swoole\WebSocket\Server $ws, $request) {
    var_dump($request->fd, $request->server);
    $ws->push($request->fd, "hello, welcome\n");
});

$ws->on('message', function (Swoole\WebSocket\Server $ws, $frame) {
    list($toFd, $message) = explode(" ", $frame->data);
    echo "Message: {$frame->fd}:{$message}\n";
    $ws->push($frame->fd, "{$message}");

    global $ws;
    // $ws->connections 遍历所有websocket连贯用户的fd
    foreach ($ws->connections as $fd) {
        // 须要先判断是否是正确的websocket连贯,否则有可能会push失败
        if ($ws->isEstablished($fd) && $fd == $toFd) {
            $ws->push($fd, "{$message}");
        }
    }
});

$ws->on('close', function (Swoole\WebSocket\Server $ws, $fd) {
    echo "client-{$fd} is closed\n";
});

$ws->start();

启动相干服务

启动容器及HTTP服务器:

docker run --rm -p 80:80 -p 8081:8081 --name swoole -v /d/swoole/www:/var/www phpswoole/swoole:4.5.9-php7.4

进入容器启动WebSocket服务器:

docker exec swoole bash
php ws.php

测试从前端页面收发音讯

关上一个标签页拜访:

另外关上一个标签页拜访:

在标签页1给标签页2发送音讯:

标签页2收到音讯:

标签页2给标签页1发送音讯:

标签页1收到音讯:

测试从后端程序收发音讯

编写一个客户端给标签页1和标签页2发送音讯:

<?php
Co\run(function () {
    $client = new Swoole\Coroutine\Http\Client("127.0.0.1", 8081);
    $ret = $client->upgrade("/");
    if ($ret) {
        $client->push("1 hello111");
        $client->push("2 hello222");
        var_dump($client->recv());
        co::sleep(0.1);
    }
});

执行客户端代码:

标签页1收到音讯:

标签页2收到音讯:


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:在-Swoole-中使用-WebSocket-服务端和客户端

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址