简体   繁体   中英

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

When a client connects a room with the clients userid is automatically created and joined. 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. And the sender joins the room with the owners userid namespace. 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.

One way is to have the client save the owner id in a cookie and recall it on every page load. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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