I wrote the following code for chat client to client(client1 to server server to client2) but I am getting an error:
Missing error handler on socket
.
TypeError: Cannot read property 'emit' of undefined
Here is my serverside code.
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(3000);
var users = {};
var reciverusers = {};
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on("users",function(data){
users[data.uid]=data.uid;
users[data.uname] =data.uname;
//console.log(data);
console.log("User Id is "+users[data.uid]);
console.log("Username is "+users[data.uname]);
console.log(users[data.uname] + " Joined with this Id: " +users[data.uid]);
//console.log("cnsle users : "+users[0]);
});
socket.on("sendmsg", function(msgdata){
console.log(msgdata);
reciverusers[msgdata.recipent]=msgdata.recipent;
reciverusers[msgdata.message]=msgdata.message;
console.log("reciver id "+reciverusers[msgdata.recipent]);
for(var name in users) {
if(users[name] === reciverusers[msgdata.recipent]) {
console.log("yes user exits");
console.log("Sending : "+ reciverusers[msgdata.message]);
io.sockets.emit("rmsg",reciverusers[msgdata.message]);
io.sockets.connected[reciverusers[msgdata.recipent]].emit("rmsg", {'msg':reciverusers[msgdata.message]});
break;
}else{
console.log("No user not exists");
}
}
});
And client side code
var username,uid;
var socket = io.connect('http://localhost');
$(".client_name").on("submit", function(){
// Tell the server about it
var username = $("#cleintname").val();
var userid = $("#cliendID").val();
socket.emit("users", {"uname": username,"uid":userid});
$(".client_name").remove();
$("#Clientnm").text(username);
return false;
});
var chat_form = $(".chatform");
chat_form.on("submit", function(){
// Send the message to the server
var reciver_id = $("#reciver_id").val();
var msg = $("#message").val();
socket.emit("sendmsg", {"recipent":reciver_id, "message":msg});
// Empty the form
$("#message").val('');
return false;
});
// Whenever we receieve a message, append it to the <ul>
socket.on("rmsg", function(data){
$("#messages").append(data);
});
it complile with this command: node app.js : compiled [OK]
When I enter or login: Its work fine [OK]
When I send message to another client: failed [Not ok] It gave me following error:
User Id is 1
Username is test
test Joined with this Id: 1
User Id is 2
Username is test2
test2 Joined with this Id: 2
here works fine and from here i tried to send message to user2/client2 that give me error
{ recipent: '1', message: 'ssfsfs' }
reciver id 1
yes user exits
Sending : ssfsfs
Missing error handler on socket
.
TypeError: Cannot read property 'emit' of undefined
I do my best to explain my code am using socket.io lib new version