Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js, Socket.io emit not working

I am making a website in Socket.io. But emit method not working in my code. I can't see any errors in my code. Here is my server code.

var io = require("socket.io").listen(server);

//Some external codes for running server in Node.js

io.on("connection", function(socket) {
    //This line is working.
    console.log("Socket connected.");

    io.on("requestNewMap", function(data) {
        //Create new map object in here.
        io.emit("responseNewMap", { mapData: map });
    });
});

And this is my client side javascript code.

var socket = io();

socket.on("responseNewMap", function(data) {
    var map = data.mapData;

    //Draw map in canvas's context.
});

//setInterval runs this method every 2 seconds.
function requestNewMap() {
    socket.emit("requestNewMap");
}
like image 464
Batın Evirgen Avatar asked Apr 14 '17 15:04

Batın Evirgen


3 Answers

This part could be wrong:

io.on("requestNewMap", function(data) {
    //Create new map object in here.
    io.emit("responseNewMap", { mapData: map });
});

I would use socket there as in:

socket.on("requestNewMap", function(data) {
    //Create new map object in here.
    socket.emit("responseNewMap", { mapData: map });
});

I think io.emit should work fine, it would just send the response to every connected client, but io.on('requestNewMap',...) won't work since requestNewMap is not an io standard event.

like image 182
Javier Conde Avatar answered Oct 13 '22 00:10

Javier Conde


change this

io.on("requestNewMap", function(data) {
    //Create new map object in here.
    io.emit("responseNewMap", { mapData: map });
});

into this

socket.on("requestNewMap", function(data) {
    //Create new map object in here.
    socket.emit("responseNewMap", { mapData: map });
});

you are adding an event listener to the server object not the client socket.

like image 31
Gntem Avatar answered Oct 13 '22 00:10

Gntem


I'm not certain, but I believe your problem is that your function on the client side is written like you are expective 'requestNewMap' to be passing along data. Instead of:

io.on("requestNewMap", function(data){

Try:

io.on("requestNewMap", function(){

OR pass an empty object or some other kind of junk data along with the emit from client side like this:

function requestNewMap() {
  socket.emit("requestNewMap", {});
}

function requestNewMap() {
  socket.emit("requestNewMap", undefined);
}

function requestNewMap() {
  socket.emit("requestNewMap", -1);
}

Hopefully this is helpful and correct!

Edit: This turned out to not be the answer to your question, but still something worth considering. If you're not passing data along you should avoid writing the event handler as if it expects data.

like image 38
Matthew Fasman Avatar answered Oct 12 '22 22:10

Matthew Fasman