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

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

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




    
    websocket client
    


    

聊天类型:       对 说:

端口配置

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

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

你可能感兴趣的:(Swoole实现基于WebSocket的群聊私聊)