Swoole实现基于WebSocket的群聊私聊

本文属于入门级文章,大佬们可以绕过啦。如题,本文会实现一个基于Swoole的websocket聊天室(可以群聊,也可以私聊,具体还需要看数据结构的设计)。

搭建Swoole环境

通过包管理工具

# 安装依赖包
$ sudo apt-get install libpcre3 libpcre3-dev
# 安装swoole
$ pecl install swoole
# 添加extension拓展
$ echo extension=swoole.so > /etc/php5/cli/conf.d/swoole.ini

源码编译安装

源码安装需要保证系统中有完善的工具包,如gcc,然后就是固定的套路。

  • ./configure
  • sudo make
  • sudo make install

这里同样不例外,大致步骤如下:

# 下载解压源码
wget https://github.com/swoole/swoole-src/archive/v1.9.1-stable.tar.gz
tar -xzvf v1.9.1-stable.tar.gz
cd swoole-src-1.9.1-stable
# 编译安装
phpize # phpize命令需要保证安装了php7-dev,具体是php几还是需要看自己安装的PHP版本
./configure
sudo make
sudo make install
# 添加配置信息,具体路径按自己的情况而定
vi /etc/php/php.ini
// 在末尾加入,路径按make install生成的为准
extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/swoole.so

上述两种方式各有利弊,选择合适自己的即可。

实现聊天室

在Swoole的wiki文档中对此有很详细的介绍,具体可以参考https://wiki.swoole.com/wiki/page/397.html 这里就不过多废话了。下面主要聊聊我眼中的最简单的聊天室的雏形:用户可以选择公聊或者私聊,然后服务器实现具体的业务逻辑。大致的数据结构应该是这个样子的:

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

服务器端逻辑

因为只是演示,服务器端做的比较简陋,大题分为两部分:框架(server.php)+具体业务(dispatcher.php)

server.php

<?php
/**
 * websocket服务器端程序
 * */

//require "一个dispatcher,用来将处理转发业务实现群组或者私聊";
require "/var/www/html/swoole/wschat/dispatcher.php";

$server = new swoole_websocket_server("0.0.0.0", 22223);

$server->on("open", function($server, $request) {
    echo "client {$request->fd} connected, remote address: {$request->server['remote_addr']}:{$request->server['remote_port']}\n";
    $welcomemsg = "Welcome {$request->fd} joined this chat room.";
    // TODO 这里可以看出设计有问题,构造方法里面应该是通用的逻辑,而不是针对某一个方法有效
    //$dispatcher = new Dispatcher("");
    //$dispatcher->sendPublicChat($server, $welcomemsg);
    foreach($server->connections as $key => $fd) {
        $server->push($fd, $welcomemsg);
    }
});

$server->on("message", function($server, $frame) {
    $dispatcher = new Dispatcher($frame);
    $chatdata = $dispatcher->parseChatData();
    $isprivatechat = $dispatcher->isPrivateChat();
    $fromid = $dispatcher->getSenderId();
    if($isprivatechat) {
        $toid = $dispatcher->getReceiverId();
        $msg = "【{$fromid}】对【{$toid}】说:{$chatdata['chatmsg']}";
        $dispatcher->sendPrivateChat($server, $toid, $msg); 
    }else{
        $msg = "【{$fromid}】对大家说:{$chatdata['chatmsg']}";
        $dispatcher->sendPublicChat($server, $msg);
    }
    /*
    $chatmsg = json_decode($frame->data, true);
    if($chatmsg['chattype'] == "publicchat") {
        $usermsg = "Client {$frame->fd} 说:".$frame->data;
        foreach($server->connections as $key => $fd) {
            $server->push($fd, $usermsg);
        }
    }else if($chatmsg['chattype'] == "privatechat") {
        $usermsg = "Client{$frame->fd} 对 Client{$chatmsg['chatto']} 说: {$chatmsg['chatmsg']}.";
        $server->push(intval($chatmsg['chatto']), $usermsg);
    }
     */
});

$server->on("close", function($server, $fd) {
    $goodbyemsg = "Client {$fd} leave this chat room.";
    //$dispatcher = new Dispatcher("");
    //$dispatcher->sendPublicChat($server, $goodbyemsg);
    foreach($server->connections as $key => $clientfd) {
        $server->push($clientfd, $goodbyemsg);
    }
});

$server->start();


dispatcher.php

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

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

    public function __construct($frame) {
        $this->frame = $frame;
        var_dump($this->frame);
        $this->clientid = intval($this->frame->fd);
        //$this->remote_addr = strval($this->frame->server['remote_addr']);
        //$this->remote_port = intval($this->frame->server['remote_port']);
    }

    public function parseChatData() {
        $framedata = $this->frame->data;
        $ret = array(
            "chattype" => self::CHAT_TYPE_PUBLIC,
            "chatto" => 0,
            "chatmsg" => "",
        );
        if($framedata) {
            $ret = json_decode($framedata, true);
        }
        $this->chatdata = $ret;
        return $ret;
    }

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

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

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

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

    public function sendPrivateChat($server, $toid, $msg) {
        if(empty($msg)){
            return;
        }
        foreach($server->connections as $key => $fd) {
            if($toid == $fd || $this->clientid == $fd) {
                $server->push($fd, $msg);
            }
        }
    }

    public function sendPublicChat($server, $msg) {
        if(empty($msg)) {
            return;
        }
        foreach($server->connections as $key => $fd) {
            $server->push($fd, $msg);
        }
    }
}

客户端

对websocket客户端来说严格来讲没多大的限制,通常我们会在移动设备或者网页上进行客户端的逻辑实现。这里拿网页版的来简单演示下:
wsclient.html

<!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">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
            </select>
            说:<input type="text" id="chatmsg" placeholder="随便来一发吧~">
            <input type="button" id="btnsend" value="发送" onclick="sendMsg()">
        </div>
    </div>
</body>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>  
<script type="text/javascript">
    var ws;
    $(function(){
        connect();
    });
    function echo(id, msg) {
        console.log(msg);
        $(id).append("<p>"+msg+"</p>");
    }
    function connect() {
        ws = new WebSocket("ws://47.104.64.90:22223");
        //ws.onopen = function(event) {echo("#chatrecord", event);}
        //ws.onclose = function(event) {echo("#chatrecord", event);}
        //ws.onerror = function(event) {echo("#chatrecord", event);}
        ws.onmessage = function(event) {
            echo("#chatrecord", event.data);
        }
    }
    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>

端口配置

由于阿里云端口的限制,这里nginx对外暴露的端口进行了更改。具体配置如下:
swoole.nginx.conf

server{

    listen 22222;
    server_name localhost;
    index index.php;
    root /var/www/html/swoole;
    location / {
        try_files $uri /index.php$is_args$args;
    
    }
    error_log /var/log/nginx/swoole_error.log;
    access_log /var/log/nginx/swoole_access.log;
    location ~ \.php$ {
        root /var/www/html/swoole;
        index index.php index.html index.htm;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

演示

演示之前,确保服务器端程序已经开启:
php server.php
运行完命令之后,没有输出就说明一切顺利。可以开启客户端进行测试了。

  • 部署测试


    部署测试
  • 公聊私聊测试


    公聊私聊测试

总结

Swoole实现WebSocket服务,其实蛮清晰的。关键还是在于如何去设计,有时候业务需求是一个不错的导向,否则越到后面代码会越臃肿,变得有“坏味道”。相比上次使用Java的Netty框架实现的websocket聊天室(https://blog.csdn.net/marksinoberg/article/details/80337779)。这二者都属于把业务逻辑从框架中剥开的实现,所以开发者可以将更多地精力放到业务逻辑上来。从而开发出更健壮的服务。

最近写的东西少的多了,不是因为懒得写,而是越写越不敢写了。面临大学毕业,正式进入社会了。很多东西不能再像之前一样随意,没有什么深度。而深刻严谨的知识没有时间的沉淀以及实践的锤炼是学不来的。不是说看到了几个名词就学会了某项技术,虚心向大佬们学习才是最切实的方法。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容