簡體   English   中英

在Socket.io上使用Redis作為PubSub

[英]Using Redis as PubSub over Socket.io

我正在創建一個聊天應用程序,使用戶可以進行私人聊天和群聊。 計划為此應用程序使用以下技術: -

NodeJs + Socket.io + Redis + CouchDB(存儲消息歷史記錄)+ AngularJS

根據我最初的研究使用Redis作為PubSub服務是比使用Socket.io作為pub-sub的更好的方法。這是因為如果不同的用戶連接到不同的服務器實例,那么在這種情況下使用套接字將產生問題,因為消息發送方式用戶1不會傳遞給用戶2(連接到服務器1的用戶1和連接到服務器2的用戶2)。

但是如果我們使用Redis,那么根據我的理解,我們必須創建新的頻道以啟用私人聊天。 而且他們對Redis的10k頻道有限制。

我懷疑是

  1. 我是否每次都需要創建新頻道以啟用兩個用戶之間的私人聊天?
  2. 如果我需要創建單獨的頻道,那么實際上是否有10K頻道的限制?
  3. 我需要一個使用Redis作為pub / sub和socket.io來啟用私人聊天的工作示例。

此致,維克拉姆

閱讀下面的文章/博客文章后,使用Redis for pub / sub over socket.io pub / sub將有助於提高可伸縮性和性能。

https://github.com/sayar/RedisMVA/blob/master/module6_redis_pubsub/README.md

https://github.com/rajaraodv/redispubsub

此外,我可以使用redis在私人聊天中創建快速POC。 這是代碼: -

var app = require('http').createServer(handler);
app.listen(8088);
var io = require('socket.io').listen(app);
var redis = require('redis');
var redis2 = require('socket.io-redis');
io.adapter(redis2({ host: 'localhost', port: 6379 }));
var fs = require('fs');

function handler(req,res){
    fs.readFile(__dirname + '/index.html', function(err,data){
        if(err){
            res.writeHead(500);
            return res.end('Error loading index.html');
        }
        res.writeHead(200);
        console.log("Listening on port 8088");
        res.end(data);
    });
}

var store = redis.createClient();   
var pub = redis.createClient();
var sub = redis.createClient();
sub.on("message", function (channel, data) {
        data = JSON.parse(data);
        console.log("Inside Redis_Sub: data from channel " + channel + ": " + (data.sendType));
        if (parseInt("sendToSelf".localeCompare(data.sendType)) === 0) {
             io.emit(data.method, data.data);
        }else if (parseInt("sendToAllConnectedClients".localeCompare(data.sendType)) === 0) {
             io.sockets.emit(data.method, data.data);
        }else if (parseInt("sendToAllClientsInRoom".localeCompare(data.sendType)) === 0) {
            io.sockets.in(channel).emit(data.method, data.data);
        }       

    });

io.sockets.on('connection', function (socket) {

    sub.on("subscribe", function(channel, count) {
        console.log("Subscribed to " + channel + ". Now subscribed to " + count + " channel(s).");
    });

    socket.on("setUsername", function (data) {
        console.log("Got 'setUsername' from client, " + JSON.stringify(data));
        var reply = JSON.stringify({
                method: 'message',
                sendType: 'sendToSelf',
                data: "You are now online"
            });     
    });

    socket.on("createRoom", function (data) {
        console.log("Got 'createRoom' from client , " + JSON.stringify(data));
        sub.subscribe(data.room);
        socket.join(data.room);     

        var reply = JSON.stringify({
                method: 'message', 
                sendType: 'sendToSelf',
                data: "Share this room name with others to Join:" + data.room
            });
        pub.publish(data.room,reply);


    });
    socket.on("joinRooom", function (data) {
        console.log("Got 'joinRooom' from client , " + JSON.stringify(data));
        sub.subscribe(data.room);
        socket.join(data.room);     

    });
    socket.on("sendMessage", function (data) {
        console.log("Got 'sendMessage' from client , " + JSON.stringify(data));
        var reply = JSON.stringify({
                method: 'message', 
                sendType: 'sendToAllClientsInRoom',
                data: data.user + ":" + data.msg 
            });
        pub.publish(data.room,reply);

    });

    socket.on('disconnect', function () {
        sub.quit();
        pub.publish("chatting","User is disconnected :" + socket.id);
    });

  });

HTML代碼

<html>
<head>
    <title>Socket and Redis in Node.js</title>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<div id="username">
    <input type="text" name="usernameTxt" /> 
    <input type="button" name="setUsername" value="Set Username" />
</div>
<div id="createroom" style="display:none;">>
    <input type="text" name="roomNameTxt" /> 
    <input type="button" name="setRooomName" value="Set Room Name" />
    <input type="button" name="joinRooomName" value="Join" />
</div>
<div id="sendChat" style="display:none;">
    <input type="text" name="chatTxt" /> 
    <input type="button" name="sendBtn" value="Send" />
</div>
<br />
<div id="content"></div>
<script>    
    $(document).ready(function() {
        var username = "anonymous";
        var roomname = "anonymous";
        $('input[name=setUsername]').click(function(){
            if($('input[name=usernameTxt]').val() != ""){
                username = $('input[name=usernameTxt]').val();
                //var msg = {type:'setUsername',user:username};
                socket.emit('setUsername',{user:username});
            }
            $('#username').slideUp("slow",function(){
                $('#createroom').slideDown("slow");
            });
        });
        $('input[name=setRooomName]').click(function(){
            if($('input[name=roomNameTxt]').val() != ""){
                roomname = $('input[name=roomNameTxt]').val();
                socket.emit('createRoom',{user:username,room:roomname});
            }
            $('#createroom').slideUp("slow",function(){
                $('#sendChat').slideDown("slow");
            });
        });
        $('input[name=joinRooomName]').click(function(){
            if($('input[name=roomNameTxt]').val() != ""){
                roomname = $('input[name=roomNameTxt]').val();
                socket.emit('joinRooom',{room:roomname});
            }
            $('#createroom').slideUp("slow",function(){
                $('#sendChat').slideDown("slow");
            });
        });

        var socket = new io.connect('http://localhost:8088');
        var content = $('#content');

        socket.on('connect', function() {
            console.log("Connected");
        });

        socket.on('message', function(message){
            //alert('received msg=' + message);
            content.append(message + '<br />');
        }) ;

        socket.on('disconnect', function() {
            console.log('disconnected');
            content.html("<b>Disconnected!</b>");
        });

        $("input[name=sendBtn]").click(function(){
            var msg = {user:username,room:roomname,msg:$("input[name=chatTxt]").val()}
            socket.emit('sendMessage',msg);
            $("input[name=chatTxt]").val("");
        });
    });
</script>
</body>
</html>

這是所有代碼基本redis pub / sub。

 var redis = require("redis"); var pub = redis.createClient(); var sub = redis.createClient(); sub.on("subscribe", function(channel, count) { console.log("Subscribed to " + channel + ". Now subscribed to " + count + " channel(s)."); }); sub.on("message", function(channel, message) { console.log("Message from channel " + channel + ": " + message); }); sub.subscribe("tungns"); setInterval(function() { var no = Math.floor(Math.random() * 100); pub.publish('tungns', 'Generated Chat random no ' + no); }, 5000); 

如果你需要弄濕腳並創建一個簡單的聊天應用程序,那么以下開發堆棧可以很好地協同工作:

  • Express.js(Node.js)
  • Redis的
  • Socket.IO

該應用程序包含一個聊天室,用戶可以加入並啟動對話。 Socket.IO負責在更新聊天計數/消息時發出事件,並使用jQuery在UI中刷新這些事件。

有關完整的文章和源代碼,請查看以下鏈接: https//scalegrid.io/blog/using-redis-with-node-js-and-socket-io/

socket.io-redis說:

通過使用socket.io-redis適配器運行socket.io,您可以在不同的進程或服務器中運行多個socket.io實例,這些實例可以相互廣播和發送事件。 所以以下任何命令:

io.emit('hello', 'to all clients');
io.to('room42').emit('hello', "to all clients in 'room42' room");

io.on('connection', (socket) => {
  socket.broadcast.emit('hello', 'to all clients except sender');
  socket.to('room42').emit('hello', "to all clients in 'room42' room except sender");
});

將通過Redis Pub / Sub機制正確地向客戶廣播。

而我猜

io.to(socket.id).emit('hello', "to client which has same socket.id");

將在不同的進程或服務器中發送私人消息。

順便說一句,我在做一個項目也需要私信。 想提出任何其他建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM