Swoole 搭建 Websocket 聊天室

一、前端CSS代码

二、服务器端 Server.php , 执行 php Server.php

on('open', function ($ws, $request) {
    // var_dump($request->fd, $request->get, $request->server);

        global $ws;

        foreach ($ws->connections as $val) {
                $ws->push($val, '{"user":"'.$request->fd.'", "message":"我上线啦"}');
        }

});

// 监听websocket消息事件

$ws->on('message', function ($ws, $frame) {
        echo "Message: {$frame->data}\n";

        $link = link_redis();

        push_array($frame->fd, $link);

        $onlineUser = getOnlineUser($link);

        global $ws;

    foreach ($ws->connections as $val) {
                $ws->push($val, '{"user":"'.$frame->fd.'", "message":"'.$frame->data.'"}');
        }


});

// 监听websocket连接关闭事件

$ws->on("close", function ($ws, $fd) {
        $link = link_redis();

        $link->sRem("test_chat", $fd);

        echo "client-{$fd} is closed\n";
});

$ws->start();

 

你可能感兴趣的:(Swoole)