使用 NodeJS 和 websockets,我正在尝试实现一个在线游戏服务器,对于一个乘数游戏,我让人们四处走动,能够看到彼此,但是当服务器产生新的敌人时,我希望能够广播向所有连接的客户端发送消息。
但是没有客户端首先向服务器发送消息。
例如 - 游戏产生一个敌人,向所有客户端发送信息。
到目前为止我的代码:
/**************************************************
** NODE.JS REQUIREMENTS
**************************************************/
var util = require("util"),
// Utility resources (logging, object inspection, etc)
io = require("socket.io"),
// Socket.IO
Player = require("./Player").Player, // Player class
Zombie = require("./Zombie").Zombie;
// Socket controller
var socket,
// Array of connected players
players,
zombies;
var level = 1,
score = 0,
levelling = false;
function init() {
// Create an empty array to store players
players = [];
zombies = [];
// Set up Socket.IO to listen on port 8000
socket = io.listen(8000);
// Configure Socket.IO
socket.configure(function() {
// Only use WebSockets
socket.set("transports", ["websocket"]);
// Restrict log output
socket.set("log level", 2);
});
// Start listening for events
setEventHandlers();
};
blah blah blah -- tl;dr -- 游戏循环:
function mainLoop(){
//Main loop for the server. Called 60 times a second. May be modified for game
speed.
//setTimeout(mainLoop, 1000/5000);
this.broadcast.emit("update");
//THIS broadcast.emit line is where the error is being thrown. I need to know how
to broadcast here without the client initializing first.
};
我尝试了一些东西,socket.broadcast.emit("update");,但没有成功。
我曾尝试遍历当前已知的用户并使用“this.emit”,但我总是得到“无法调用未定义的方法发射”,太烦人了。
但是当我让客户端首先发送消息时,例如,当客户端移动时,它会向服务器发送一些信息,服务器会做出以下反应:
function onSocketConnection(client) {
util.log("New player has connected: " + client.id);
// Listen for client disconnected
client.on("disconnect", onClientDisconnect);
// Listen for new player message
client.on("new player", onNewPlayer);
// Listen for move player message
client.on("move player", onMovePlayer);
//listen for deaths
client.on("death", onPlayerDeath);
//listen for not moved message, to stop sprite animation
client.on("not moved", notMoved);
};
// Player has moved
function onMovePlayer(data) {
// Find player in array
var movePlayer = playerById(this.id);
// Player not found
if (!movePlayer) {
util.log("Player not found: "+this.id + " when asking if moved");
return;
};
// Update player position
movePlayer.setX(data.x);
movePlayer.setY(data.y);
movePlayer.setDir(data.dir);
// Broadcast updated position to connected socket clients
this.broadcast.emit("move player", {id: movePlayer.id, x:
movePlayer.getX(), y:movePlayer.getY(), dir: movePlayer.getDir()});
};
然后“this.broadcast.emit”没有问题。不抛出错误。