0

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

Drew Gaynor
  • 8,292
  • 5
  • 40
  • 53

1 Answers1

0

You've binded Your app to 3000-th port, and set socket.io to work with http module that listens on 3000.

So You've to change on clientside this:

var socket = io.connect('http://localhost');

to this:

var socket = io.connect('http://localhost:3000');

or just:

var socket = io.connect();



also from Your code:

users[data.uid]=data.uid;
users[data.uname] =data.uname;

I don't see any logic here :) Why not to keep it like:

users[data.uid] = {uid: data.uid, uname: data.uname}
sockets[socket.id] = socket;
if(!users[data.uid].sockets) {
  users[data.uid].sockets = [];
}
users[data.uid].sockets.push(socket);
num8er
  • 18,604
  • 3
  • 43
  • 57
  • suspect that's a typo in OP's transcription to SO - the client would not be able to connect at all and he is clearly communicating between the two. – caasjj Sep 18 '15 at 20:44
  • so what i do to connect ? –  Sep 18 '15 at 20:48
  • 2
    are you not connecting already? As @num8er said, if you serve on port 3000 and have client try to connect on default port (80), you won't connect. – caasjj Sep 18 '15 at 21:11
  • 1
    @caasjj, seems like Aryan has gone, maybe angry that nobody helped (: – num8er Sep 18 '15 at 21:52
  • why u use socket.id ? if i have user id already soo why should i use one of that socket ? –  Sep 19 '15 at 14:24
  • 1
    Cuz anyone can replace id with another's. Socket id is like session id unique hash, and cuz it's not number it's more secure, so I keep relation between them. Also, one user can login from desktop, mobile and etc, so each of them has its socket.id. when user gets message, this message must be routed to all of user's sockets. – num8er Sep 19 '15 at 14:27
  • 1
    Believe me in the end You'll do like mine :) – num8er Sep 19 '15 at 14:28