Skip to content

Instantly share code, notes, and snippets.

@davidutzus
Last active October 24, 2017 23:29
Show Gist options
  • Select an option

  • Save davidutzus/4e3b2ac587f989f11ece0d0b0cf99f52 to your computer and use it in GitHub Desktop.

Select an option

Save davidutzus/4e3b2ac587f989f11ece0d0b0cf99f52 to your computer and use it in GitHub Desktop.
Example of setting-up dynamic "rooms" for socket.io private messaging.
//tested with:
// "express": "^4.16.2",
// "request": "^2.83.0",
// "socket.io": "^2.0.4"
// set-up a connection between the client and the server
var socket = io.connect();
// let's assume that the client page, once rendered, knows what room it wants to join
var room = "abc123";
socket.on('connect', function() {
// Connected, let's sign-up for to receive messages for this room
socket.emit('room', room);
});
socket.on('message', function(data) {
console.log('Incoming message:', data);
});
// show a message when other user is typing
var typeTimer;
var typingInterval = 1000;
$$(chatBar.textarea).on("keyup keydown change blur", function (e) {
if (e.type === 'keyup') {
clearTimeout(typeTimer);
typeTimer = setTimeout(function () {
socket.emit("notify typing", {
name: sender.username
}); //sending data to server
}, typingInterval);
}
});
socket.on("typing", function (data) {
$('.typing-notification').html(data.name + " is typing").slideDown();
setTimeout(function () {
$('.typing-notification').slideUp().html('');
}, 3000);
});
// attach Socket.io to our HTTP server
io = socketio.listen(server);
// handle incoming connections from clients
io.sockets.on('connection', function(socket) {
// once a client has connected, we expect to get a ping from them saying what room they want to join
socket.on('room', function(room) {
socket.join(room);
});
});
// now, it's easy to send a message to just the clients in a given room
room = "abc123";
io.sockets.in(room).emit('message', 'what is going on, party people?');
// send a notify typing on client
socket.on("notify typing", function (data) {
socket.broadcast.to(chatRoom).emit('typing', data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment