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)。这二者都属于把业务逻辑从框架中剥开的实现,所以开发者可以将更多地精力放到业务逻辑上来。从而开发出更健壮的服务。

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

猜你喜欢

转载自blog.csdn.net/Marksinoberg/article/details/80644489