简体   繁体   English

Socket.io将两个客户端添加到房间

[英]Socket.io add two clients to room

I'm trying to implement private messaging in an app im creating using express 3 and socket.io 我正在尝试使用express 3和socket.io在app中实现私人消息

When a client connects a room with the clients userid is automatically created and joined. 当客户端将房间与客户端连接时,将自动创建并加入userid。 This is mainly for notifications and that sort of stuff. 这主要是针对通知和那种东西。 Now im trying to make this work for private chat too.When a user clicks the send button, the message gets sent along with the userid of the sender (from session userid) and the userid of the owner thats grabbed from a hidden field or attribute of element. 现在我也尝试将此工作用于私人聊天。当用户单击发送按钮时,消息将与发件人的用户ID(来自会话用户ID)以及从隐藏字段或属性中抓取的所有者的用户ID一起发送元素。 And the sender joins the room with the owners userid namespace. 发件人使用所有者userid名称空间加入会议室。 The problem with this is that when the sender goes to another page or refresh the browser he is diconnected from the room, and doesnt recieve any further messages from the owner. 这样做的问题是,当发件人转到另一个页面或刷新浏览器时,他会被从房间中取消,并且不会收到来自所有者的任何进一步消息。 He has to send a new message to rejoin the owners room. 他必须发送一条新消息才能重新加入主人房间。 Now how do i percist the connection to the owners room? 现在,我如何确定与业主房间的连接? Or am i doing this all wrong? 或者我这样做是错的吗? Is there a better or standard way to achieve this? 有没有更好或更标准的方法来实现这一目标?

SERVER: 服务器:

io.on('connection', function (socket) {
    var sh = socket.handshake;

    socket.join(sh.session.userid);

    socket.on('chat', function (data) {
        if (data.user) {
            socket.join(data.owner);
        }
        io.sockets.in(data.owner).emit('chat',
            {user: sh.session.user, message: data.message});
    });
});

CLIENT: 客户:

var socket = io.connect('https://localhost/');

$('#send_message').click(function (e) {
    socket.emit('chat',{message: $('.message').val(),
         user:$('#user'), owner:$('#owner')} //Get this from hidden fields in chat form );
    e.preventDefault();
});

socket.on('chat', function (data) {
    $('ol').prepend('<li>' + data.user + '<br />' + data.message + '</li>');
});

Right. 对。 Because when you reload the page, the server gets a "client disconnected" message and unsubscribes the socket. 因为当您重新加载页面时,服务器会收到“客户端断开连接”消息并取消订阅套接字。 The client will need to re-emit a 'chat' message (with same owner id) in order to get back onto the private feed. 客户端需要重新发出“聊天”消息(具有相同的所有者ID)才能返回私有Feed。

One way is to have the client save the owner id in a cookie and recall it on every page load. 一种方法是让客户端将所有者ID保存在cookie中,并在每次加载页面时调用它。 Alternatively, you could have the server store and recall this info using a session cookie (http://www.senchalabs.org/connect/session.html), which, in essence, is much like the first option. 或者,您可以让服务器存储并使用会话cookie(http://www.senchalabs.org/connect/session.html)调用此信息,这实际上与第一个选项非常相似。

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

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