SocketIO, can't send emit data from client

别等时光非礼了梦想. 提交于 2019-12-24 05:15:14

问题


I'm having the most odd problem trying to send data from a client browser to my node server using SocketIO. Sending from server to client works just fine, but the other way around I get an undefined error. Here's a quick bit of what it looks like, super simple.

Node Server (app.js)

io.on("connection", function(socket) {
  socket.on("pageReady", function(data) {
    console.log('pageReady called');
    console.log(data);
    return socket.emit('newline', '###SOCKET STARTED###');
  });
 socket.on("disconnect", function() {
    return console.log('disconnected');
  });
});

Browser (client.js)

var socket;

socket = io.connect("http://localhost:5678");

socket.on("newline", function(data) {
  return $('#socketData').append('<li>' + data + '</li>');
});

socket.emit("pageReady", "test");

Super simple, right? Nothing special. When I emit from server, works fine, however when the client calls "pageReady". node responds with this.

/Volumes/HOME/Users/user/git/sockettest/app.js:89
    console.log(data);
                ^
ReferenceError: data is not defined

Data should be returning "test", but isn't. What am I doing wrong?


回答1:


Your client should listen for the socket connection before attempting to emit to it:

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

socket.on("newline", function(data) {
  return $('#socketData').append('<li>' + data + '</li>');
});

socket.on("connect", function() {
  socket.emit("pageReady", "test");
});


来源:https://stackoverflow.com/questions/27369553/socketio-cant-send-emit-data-from-client

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