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

编写前端及服务器端代码

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



    
        
        WebSocket
    
    
        
        
        

创建一个HTTP服务器文件,用来接收前端的页面请求:

#!/usr/bin/env php
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
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

测试从前端页面收发消息

打开一个标签页访问:

image-20201211183350115.png

image-20201211183421049.png

另外打开一个标签页访问:

image-20201211183456901.png

image-20201211183519011.png

在标签页1给标签页2发送消息:

image-20201211183556088.png

标签页2收到消息:

image-20201211183639729.png

标签页2给标签页1发送消息:

image-20201211183719232.png

标签页1收到消息:

image-20201211183734565.png

测试从后端程序收发消息

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

upgrade("/");
    if ($ret) {
        $client->push("1 hello111");
        $client->push("2 hello222");
        var_dump($client->recv());
        co::sleep(0.1);
    }
});

执行客户端代码:

image-20201211183905288.png

image-20201211184219977.png

标签页1收到消息:

image-20201211184244614.png

标签页2收到消息:

image-20201211184300566.png

你可能感兴趣的:(php,swoole,websocket)