Socket.IO TypeError: Cannot read property 'emit' of undefined

為{幸葍}努か 提交于 2019-12-11 16:21:36

问题


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


回答1:


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);


来源:https://stackoverflow.com/questions/32659864/socket-io-typeerror-cannot-read-property-emit-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!