简体   繁体   English

无法使用Socket.IO向客户端广播

[英]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. 我的node.js服务器有一个间隔设置,可以每60秒调用一次名为“ spawnItem”的函数。 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 TypeError:无法调用未定义的方法“ emit”

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. 我在它下面还有socket = io.listen(4339) 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. 我的目标是让服务器告诉客户端每60秒以某个x,y坐标生成一个项目,但是我无法让服务器发送消息。

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 : 相反,您需要使用listen返回的对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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