繁体   English   中英

私人聊天消息使用Node.js,Socket.io,Redis in PHP

[英]Private Chat Messaging using Node.js, Socket.io, Redis in PHP

我正在为我的php应用程序中的一个实时私人消息系统工作。 我的代码一起为所有用户服务。 但我需要私人消息系统作为一对一的消息。

在设置节点和redis后,我可以得到我需要的消息数据:这里是代码::

前端:: 1.我使用表单 - 用户名,消息和发送按钮

和通知JS:

$( document ).ready(function() {

    var socket = io.connect('http://192.168.2.111:8890');

    socket.on('notification', function (data) {
        var message = JSON.parse(data);
        $( "#notifications" ).prepend("<p> <strong> " + message.user_name + "</strong>: " + message.message + "</p>" );

    });

});

服务器端js:

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');

server.listen(8890);

var users = {};
var sockets = {};

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

    console.log(" New User Connected ");
    // instance of Redis Client
   var redisClient = redis.createClient();
   redisClient.subscribe('notification');

   socket.on('set nickname', function (name) {
       socket.set('nickname', name, function () {
           socket.emit('ready');
       });
   });

  socket.on('msg', function () {
    socket.get('nickname', function (err, name) {
        console.log('Chat message by ', name);
    });
  });


   redisClient.on("message", function(channel, message)
   {
     // to view into terminal for monitoring
     console.log("Message from: " + message + ". In channel: " + channel + ". Socket ID "+ socket.id );

     //send to socket
     socket.emit(channel, message);
   });

   redisClient.on('update_chatter_count', function(data)
   {
      socket.emit('count_chatters', data);
   });

   //close redis
   socket.on('disconnect', function()
   {
      redisClient.quit();
   });

 });

HTML ::

<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<form .....>
<input ....... >
</form>
<div id="notifications" ></div>

总体输出:

John : Hello
Kate : Hi
Others: .....

上面的代码在我的php应用程序中运行良好。 现在我想建立私人或一对一的消息系统。

我需要为用户添加用户名或电子邮件或唯一套接字ID的方式。 我对私人消息没有更多的想法。 我试图在网上找到但却失败了。

**如何在我的php应用程序中设置私人消息? **

变量的基本初始化: -

通常使mapOfSocketIdToSocket的 MAP发送您要从前端发送消息的特定用户的用户ID。 在服务器中找到与userid映射的套接字obeject ,并在该套接字中发出消息。 以下是该想法的示例(不是完整代码)

  var io = socketio.listen(server);
  var connectedCount = 0;
  var clients = [];
  var socketList = [];
  var socketInfo = {};
  var mapOfSocketIdToSocket={};

  socket.on('connectionInitiation', function (user) {
      io.sockets.sockets['socketID'] = socket.id;
      socketInfo = {};
      socketInfo['userId']=user.userId;
      socketInfo['connectTime'] = new Date();
      socketInfo['socketId'] = socket.id;
      socketList.push(socketInfo);

      socket.nickname = user.name;
      socket.userId= user.userId;

      loggjs.debug("<"+ user.name + "> is just connected!!");

      clients.push(user.userId);
      mapOfSocketIdToSocket[socket.id]=socket;
  }
  socket.on('messageFromClient', function (cMessageObj, callback) {
     for(var i=0; i<socketList.length;i++){
       if(socketList[i]['userId']==cMessageObj['messageToUserID']){ // if user is online
        mapOfSocketIdToSocket[socketList[i]['socketId']].emit('clientToClientMessage', {sMessageObj: cMessageObj});
        loggjs.debug(cMessageObj);
      }
    }
  })

您可能想要私人一对多或一对一的房间概念(如果只有两个成员) http://williammora.com/nodejs-tutorial-building-chatroom-with/

我建议你使用socketIO命名空间,它允许你从/向特定的通信“通道”发送/发出事件。

以下是有关房间和命名空间的socketIO文档的链接

http://socket.io/docs/rooms-and-namespaces/

干杯

一种解决方案可以是向具有特定套接字ID的人发送消息。 由于您已经在使用redis,因此您可以在用户加入时将用户的详细信息和套接字ID存储在redis中,然后在每次要向其发送消息时通过redis获取套接字ID来向用户发送消息。 像这样调用事件

socket.emit('send private')来自前端

并在后端处理

socket.on('send private'){//在这里做redis的东西}

使用Pusher 它提供频道使用,无需任何额外代码即可进行私聊

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM