Swoole实现私聊群聊

代码

https://github.com/7117/Graphic-live-broadcasting-site/tree/master/swoole%20example/chatroom

 

数据结构

 # 公聊结构
 {
     "chattype":"publicchat",
     "chatto":"0",
     "chatmsg":"具体的聊天逻辑"
 }
 # 私聊结构
 {
     "chattype":"privatechat",
     "chatto":"2614677",
     "chatmsg":"具体的聊天逻辑"
 }

页面

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket client</title>
    <style type="text/css">
        .container {
            border: #ccc solid 1px;
        }

        .up {
            width: 100%;
            height: 200px;
        }

        .down {
            width: 100%;
            height: 100px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="up" id="chatrecord">
    </div>
    <hr>
    <div class="down">
        聊天类型:
        <select id="chattype">
            <option value="publicchat">公聊</option>
            <option value="privatechat">私聊</option>
        </select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        对
        <select id="chatto">
        </select>
        说:<input type="text" id="chatmsg" placeholder="聊聊天">
        <input type="button" id="btnsend" value="发送">
    </div>
</div>
</body>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">

    $(document).ready(function () {
        var ws;

        ws = new WebSocket("ws://chat.room.com:8811");

        ws.onopen = function (evt) {
            if (ws.readyState == 1) {
                $("#chatrecord").append("<p>" + '这是来自客户端的欢迎' + "</p>");
            }
        }

        ws.onmessage = function (event) {

            var data = $.parseJSON(event.data);

            $("#chatrecord").append("<p>" + data.msg + "</p>");

            console.log(data.total.length);
            console.log($("#chatto option").length);

            $(data.total).each(function (k, v) {
                if( data.total.length > $("#chatto option").length){
                    $("#chatto").append("<option id='k'>" + v + "</option>");
                }
            })
        }

        ws.onclose = function (event) {
            $("#chatrecord").append("<p>" + 关闭 + "</p>");
        }

        ws.onerror = function (event) {
            $("#chatrecord").append("<p>" + event.data + "</p>");
        }

        $("#btnsend").click(function sendMsg() {
            var chatmsg = $("#chatmsg").val();
            var chattype = $("#chattype").val();
            var chatto = $("#chatto").val();
            var msg = JSON.stringify({"chattype": chattype, "chatto": chatto, "chatmsg": chatmsg});
            if (msg != "" && chatmsg != "") {
                ws.send(msg);
                $("#chatmsg").val("");
            }
        })

    })
</script>
</html>

消息处理

<?php

/**
 * 用于实现公聊私聊的特定发送服务。
 * */
class Dispatcher
{

    const CHAT_TYPE_PUBLIC = "publicchat";
    const CHAT_TYPE_PRIVATE = "privatechat";

    public $frame = '';

    public $clientid = '';

    public $chatData = '';

    public function __construct($frame)
    {
        $this->frame = $frame;
        $this->clientid = intval($this->frame->fd);
        print_r($frame);
    }

    public function getChatData()
    {
        $frameData = $this->frame->data;

        if ($frameData) {
            $frameData = json_decode($frameData, true);
            $this->chatData = $frameData;
            return $this->chatData;
        }
    }

    public function getSenderId()
    {
        return $this->clientid;
    }

    public function getReceiverId()
    {
        return intval($this->chatData['chatto']);
    }

    public function isPrivateChat()
    {
        $chatdata = $this->getChatData();
        return $chatdata['chattype'] == self::CHAT_TYPE_PUBLIC ? false : true;
    }

    public function sendPrivateChat($server, $toid, $msg)
    {

        foreach ($server->connections as $key => $fd) {
            if ($toid == $fd || $this->clientid == $fd) {
                $info = [
                    'msg' => $msg,
                ];
                $server->push($fd, json_encode($info));
            }
        }

        return;
    }

    public function sendToEvery($server, $msg)
    {

        $total = $server->getClientList();

        foreach ($server->connections as $key => $fd) {
            $info = [
                'msg' => $msg,
                'total' => $total
            ];

            $server->push($fd, json_encode($info));
        }

        return;

    }
}

服务器

<?php

include "./dispatcher.php";

class Server
{
    public function __construct()
    {
        error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);

        $ws = new swoole_websocket_server("0.0.0.0", 8811);

        //设置静态页
        $ws->set([
            'enable_static_handler' => true,
            'document_root' => "./",
            'worker_num' => 5
        ]);


        $ws->on("open", function ($ws, $request) {
            echo "open:client {$request->fd}" . PHP_EOL;

            $count = count($ws->connections);
            //获取所有的连接  进行遍历展示
            $totalConn = $ws->getClientList();

            foreach ($ws->connections as $key => $fd) {
                $welcomeWord = "";
                $info = [
                    'msg' => $welcomeWord,
                    'total' => $totalConn
                ];

                $ws->push($fd, json_encode($info));
            }

        });

        // $frame 是 swoole_websocket_frame 对象,包含了客户端发来的数据帧信息
        $ws->on("message", function ($ws, $frame) {
            //接收客户端的信息
            $dispatcher = new Dispatcher($frame);
            //获取
            $chatdata = $dispatcher->getChatData();
            $fromid = $dispatcher->getSenderId();
            $toid = $dispatcher->getReceiverId();
            $isprivatechat = $dispatcher->isPrivateChat();

            //私聊
            if ($isprivatechat) {
                $msg = "【{$fromid}】对【{$toid}】说:{$chatdata['chatmsg']}";
                $dispatcher->sendPrivateChat($ws, $toid, $msg);
                //公聊
            } else {
                $msg = "【{$fromid}】对大家说:{$chatdata['chatmsg']}";
                $dispatcher->sendToEvery($ws, $msg);
            }
        });

        $ws->on("close", function ($ws, $fd) {
            if ($ws->isEstablished) {
                foreach ($ws->connections as $key => $fd) {
                    $goodbyeMag = "CLOSE:Client {$fd} leave this chat room.";

                    $info = [
                        'msg' => $goodbyeMag,
                    ];

                    $ws->push($fd, json_encode($info));
                }
            }
        });

        $ws->start();


    }
}


$ws = new Server();


 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我了解你的问题。对于使用 ThinkPHP 框架和 Swoole 扩展实现聊天的问题,具体的思路如下: 1. 安装 Swoole 扩展:可以通过编译源码或者安装扩展包的方式进行安装。建议使用 PECL 方式安装,可以通过以下命令安装: ```sh pecl install swoole ``` 2. 创建 Swoole 服务器:在 ThinkPHP 中,可以通过创建一个 Swoole 服务器的任务来实现聊天功能。具体来说,可以在 `application/command` 目录下创建一个 `ChatServer.php` 文件,然后在该文件中编写 Swoole 服务器的逻辑。 3. 实现 WebSocket 协议:由于聊天功能需要使用 WebSocket 协议,因此需要在 Swoole 服务器中实现相应的逻辑。可以使用 Swoole 提供的 `WebSocket\Server` 类来实现 WebSocket 服务器。 4. 处理客户端请求:在 Swoole 服务器中,可以通过注册回调函数来处理客户端的请求。可以在 `onMessage` 回调函数中接收客户端发送的消息,并将消息广播给所有的客户端。 5. 实现聊天室功能:可以使用 Swoole 提供的 `Table` 类来实现聊天室功能。可以在 `onOpen` 回调函数中为每个客户端分配一个唯一的 ID,并将其与对应的 WebSocket 连接关联起来。然后在 `onMessage` 回调函数中,可以将客户端发送的消息存储到 `Table` 中,并在 `onMessage` 回调函数中广播消息给所有的客户端。 以上就是使用 ThinkPHP 和 Swoole 实现聊天功能的基本思路。具体的实现细节可以根据需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值