Reputation: 1484
I am trying to have it so when a user disconnects from my chat room, it pops up with " has left chat room".
Here is my server code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('chat/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.on('disconnect', function(nickname){
io.emit('disconnect', nickname);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
And here is my client code:
var socket = io();
var nickname;
var leaving;
$('messageForm').submit(function(){
socket.emit('chat message', (nickname + ": " + $('#m').val()));
$('#m').val('');
return false;
});
$('#nicknameForm').submit(function(){
nickname = $('#nickname').val();
if(nickname ==''){
alert("Please enter a value");
}else{
$( "#dialog" ).dialog( "close" );
leaving = nickname + " has left";
}
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
socket.on('disconnect', function(nickname){
socket.emit('disconnect message', nickname);
});
At the moment, nothing appears at all, and I'm not too sure why.
Upvotes: 0
Views: 582
Reputation: 579
You need to emit a unique event to the clients when another client disconnects.
Change the following:
socket.on('disconnect', function() {
io.emit('disconnect', nickname);
});
To something like this:
socket.on('disconnect', function() {
socket.broadcast.emit('user disconnect', nickname);
});
And add this to your client code:
socket.on('user disconnect', function(nickname){
$('#messages').append($('<li>').text(nickname+' has left the channel.'));
});
Upvotes: 1