基于Redis发布订阅和websocket实现聊天室功能

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于Redis发布订阅和websocket实现聊天室功能相关的知识,希望对你有一定的参考价值。

参考技术A 同时在做消息的持久化的时候,可以利用Redis的Zset的特性来对历史消息进行存储。

Swoole+Redis+webSocket实现点对点即时聊天

Swoole+Redis+webSocket实现点对点即时聊天

场景

Swoole+Redis+webSocket实现点对点即时聊天。

webSocket服务端代码

我们需要通过Laravel Command来实现,因为Swoole只能运行在PHP CLI模式下。

1.生成Command类

php artisan make:command SwooleServer

2.编写webSocket Server逻辑

<?php

namespace App\\Console\\Commands;

use Illuminate\\Console\\Command;
use Illuminate\\Support\\Facades\\Redis;

class SwooleServer extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole:server';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'swoole websocket';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $server = new \\Swoole\\WebSocket\\Server("0.0.0.0", 9502);
 
        $server->on('open', function($server, $req) {
            echo "connection open: {$req->fd}\\n";
        });
        
        $server->on('message', function($server, $frame) {
            echo "received message: {$frame->data}\\n";

            $receive_data=json_decode($frame->data);
            $redis=new \\Redis();
            $redis->connect('127.0.0.1', 6379);
            $redis->auth('123456');

            if($receive_data->type=='bind'){
                //关系绑定
                $redis->set('fd_'.$receive_data->name,$frame->fd);
                $redis->set('name_'.$frame->fd,$receive_data->name);
            }else{
                //消息发送
                $data['fd']=$frame->fd;
                $data['name']=$receive_data->name;
                $data['data']=$receive_data->msg;
                $server->push($redis->get('fd_'.$receive_data->touser), json_encode($data));
                $server->push($frame->fd, json_encode($data));
            }
        });
        
        $server->on('close', function($server, $fd) {
            echo "connection close: {$fd}\\n";

            //取消关系绑定
            $redis=new \\Redis();
            $redis->connect('127.0.0.1', 6379);
            $redis->auth('123456');
            
            $redis->del('fd_'.$redis->get('name_'.$fd));
            $redis->del('name_'.$fd);
        });
        
        $server->on('Shutdown', function($server) {
            //kill -15 PID 才会触发
            echo "Shutdown。。。\\n";

            $redis=new \\Redis();
            $redis->connect('127.0.0.1', 6379);
            $redis->auth('123456');

            //取消所有关系绑定
            foreach($server->connections as $fd)
            {
                $redis->del('fd_'.$redis->get('name_'.$fd));
                $redis->del('name_'.$fd);
            }
        });
        
        $server->start();
    }
}

前端代码

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<style>
    ul,li{list-style: none;padding: 0;margin: 0;}
    body{width: 50%;float: left;margin: 5px 25%;}
    .msg_box{width: 100%;border:1px solid #ddd;height: 500px; float: left;overflow: scroll;}
    .msg_box li{padding: 10px;border-bottom:1px solid #ddd;}
    .op_box{width: 100%;float: left;}
    .op_box textarea{width: 96%;float: left;padding: 2%;border:1px solid #ddd;height: 50px;resize: none;}
    .op_box a{width: 200px;display: block;float: right;height: 30px;line-height: 30px;background: #ddd;color: black;text-align: center;text-underline-style: none;margin-top: 5px;}
 
</style>
<body>
<ul class="msg_box"></ul>
<div class="op_box">
    <textarea name="msg" placeholder="请输入消息"></textarea>
    <a href="javascript:;" class="send_btn">发送</a>
</div>
</body>
<script>
    var data='';
    var name = window.prompt('请输入昵称', 'jungshen');
    var touser=window.prompt('请输入好友昵称', 'mirror');
    $('title').html('您是:'+name+'正在与'+touser+'聊天_'+$('title').html());
    if(name){
        var ws = new WebSocket("ws://172.20.31.192:9502");
 
        ws.onopen = function(evt) {
            console.log("Connection open ...");
            //ws.send("Hello WebSockets!");
            data={'name':name,'type':'bind'}
            ws.send(JSON.stringify( data ));
        };
 
        ws.onmessage = function(evt) {
            console.log( "Received Message: " + evt.data);
            dataObj=eval('('+evt.data+')');
            $('.msg_box').append('<li>'+dataObj.name+':'+dataObj.data+'</li>')
            //ws.close();
        };
        ws.onclose = function(evt) {
            console.log("Connection closed.");
        };
        ws.onerror = function(evt) {
            console.log('error');
        };
    }
 
 
    $('.send_btn').click(function(){
        var msg=$('textarea').val();
        if(msg){
            data={'name':name,'msg':msg,'type':'msg','touser':touser}
            ws.send(JSON.stringify( data ));
            $('textarea').val('');
        }
    });
    document.onkeydown=function(event){
        if(event.keyCode==13)
        {
            $('.send_btn').click();
            return false;
        }
    }
 
</script>
</html>
```
# 预览
![在这里插入图片描述](https://img-blog.csdnimg.cn/44d9a3ef07f44d979429aaeee7f53ef1.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAd2djaGVufg==,size_20,color_FFFFFF,t_70,g_se,x_16)

以上是关于基于Redis发布订阅和websocket实现聊天室功能的主要内容,如果未能解决你的问题,请参考以下文章

2020-04-05-SpringBoot+WebSocket基于Redis订阅发布实现集群化

websocket+nodejs+redis实现消息订阅和发布系统

Swoole+Redis+webSocket实现点对点即时聊天

Swoole+Redis+webSocket实现点对点即时聊天

如何实现从 Redis 中订阅消息转发到 WebSocket 客户端

Webflux,使用Websocket如何防止订阅两次反应式redis消息操作