Swoole实现私聊群聊
生活随笔
收集整理的這篇文章主要介紹了
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> 對<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;} }服務器
<?phpinclude "./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();?
總結
以上是生活随笔為你收集整理的Swoole实现私聊群聊的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL索引面试题:优化 索引分类
- 下一篇: Linux之shell中的(),(())