简体   繁体   中英

Can't broadcast to clients using Socket.IO

My node.js server has an interval setup to call a function called 'spawnItem' every 60 seconds. When this function is called, it executes this piece of code:

io.sockets.emit("spawn item", {x: 10, y: 10});

Every time the server attempts to execute this it closes immediately and says:

TypeError: Cannot call method 'emit' of undefined

According to everything I've read online it should be fine.

var util = require("util"),object inspection, etc),
io = require("socket.io"),
Player = require("./Player").Player;

This code is at the top of the page which I assume is all that is needed, or am I wrong? I also have socket = io.listen(4339) below it. Sockets are all configured below etc etc.

I have also tried doing:

socket.broadcast.emit("spawn item", bla bla bla);
socket.emit("spawn item", bla bla bla);

My goal is to have the server tell the client to spawn an item at certain x, y coordinates every 60 seconds, however I can't get the server to send a message out.

Thanks!

You're not posting a lot of information, but I think you're using the wrong object:

var io = require('socket.io');
io.sockets.emit(...); // Fails, wrong object.

Instead, you need to use the object returned by listen :

var io = require('socket.io').listen(4339);
io.sockets.emit(...); // Correct use.

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