I am new at node.js and socket.io, following the 'get started' code from official socket.io website, I wrote simple chat. Then I wanna create different rooms, like in messengers. But relying on official documentation, I can't do this as myself... Here is my server code:
io.on('connection', function(socket) {
var room_name = socket.request.headers.referer; // link of the page, where user connected to socket
// connecting to room
socket.join(room_name, function(){
//trying to send messages to the current room
io.to(room_name, function () {
socket.on('chat message', function (msg) {
io.emit('chat message', msg);
});
});
});
});
And my client side code:
$(function () {
var socket = io();
//when we submit our form
$('form').submit(function(){
//we are sending data to socket.io on server
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
//And then we are creating message in our html code
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
via Bim Bam
No comments:
Post a Comment