简体   繁体   中英

NodeJS/SocketIO Socket will not emit

I'm trying to 'emit' data to the server, but nothing is happening. The console says that I've connected, but it won't log anything whenever I try to emit the specific command.

Clientside (JQuery/JS):

    var ip = "";
    $.ajax({
        url : "../host",
        success : function(result){
            ip = result;
        }
    });

    var socket = io.connect(ip);
    socket = io('/admin');

    socket.on('add_task', function(name, event, command, args) {
        AddTask(name, event, command, args); //I get this data from the server
    });

    socket.on('remove_task', function(name) {
        DeleteTask(name); //I get this data from the server.
    });

    $("#addTask").click(function() {
        var args = ["add", $("#nameData").val(), $("#eventData").val(), $("#commandData").val(), $("#argData").val()];
        socket.emit("task", args); //This won't emit anything.
        $("#add-modal").modal("hide");
    });

Serverside (NodeJS):

admin.on('connection', function(socket) {
console.log("An admin has connected."); //This logs

task.get().forEach(function(tsk) {
    var tdata = tsk.split(':');
    admin.emit('add_task', tdata[0], tdata[1], tdata[2], tdata[3]); //This sends
});

admin.on('task', function(args) {
    console.log(args); //This doesn't log
});
});

You need to listen for the event on the connected socket, like so:

admin.on('connection', function(socket) {
  socket.on('task', function(args) {
    console.log(args);
  });
});

This is because the event comes from the connected socket, otherwise socket.io would have no way of knowing which socket the event came from and the event's associated data would be meaningless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM