我有一个使用socket.io将数据发送给用户节点JS服务器将数据发送到特定的用户。到目前为止,我可以向请求它的用户或所有用户发送数据。但我想知道一种将数据发送给其他人请求的特定用户的方法。在这种情况下,它是一个您可以主持游戏的网站。所以当另一个用户想加入时,我想发送数据给托管该游戏的人告诉他们这个用户想加入。这里是我的代码使用插座IO
exports.Server = Server = function()
{
this.userId = 1;
this.userName = "Guest";
};
Server.prototype.initialise = function(port)
{
//Create the server using the express module
this.server = http.createServer(app);
//Declare the 'public' folder and its contents public
app.use(express.static('public'));
//Listen to any incoming connections on the declared port and start using websockets
this.server.listen(port);
this.startSockets();
this.em = new events();
consoleLog('SERVER', 'Running on port: ' + port);
};
Server.prototype.startSockets = function()
{
//When a user connects to the server on the 'game' socket
this.socket = io.listen(this.server);
this.socket.of('game').on('connection', function(user)
{
//Set their usedId and username
user.userId = this.userId;
user.userName = this.userName + " " + this.userId;
//Increment the user id by 1 so each user with get a unique id
this.userId++;
//Send a response back to the client with the assigned username and user id and initialise them
user.emit('response', user.userId, user.userName);
this.em.emit('initialiseUser', user.userId, user.userName);
//Tell the server to log the user that has just connected
consoleLog('SERVER', user.userName + ' has connected. ID: ' + user.userId)
//Server listeners from the client
//If the user wants to host a game, take the game settings they requested
user.on('hostGame', function(boardSize, gameMode, gameNote)
{
//Tell the app to request a new hosted game with the users information and settings
this.em.emit('hostGame', user.userId, user.userName, boardSize, gameMode, gameNote);
}
.bind(this));
//If the user wants to cancel the game they are hosting
user.on('cancelHostGame', function()
{
//Tell the app to request to cancel their game passing in the users information
this.em.emit('cancelHostGame', user.userId, user.userName);
}
.bind(this));
user.on('joinGame', function(user.id, user.userName, opponentId)
{
//Need to tell the user with the opponent Id, that the user.id wants to join
}
.bind(this));
//When a user disconnects
user.on('disconnect', function()
{
//Tell the app to request to cancel the game the user was hosting
this.em.emit('cancelHostGame', user.userId, user.userName);
//Tell the server who disconnected
consoleLog('SERVER', user.userName + ' has disconnected. ID: ' + user.userId)
}
.bind(this));
}
.bind(this));
};
function updateGamesList(socket, hostedGames)
{
//Emit the updateGameList function on the client and pass through the array of games being hosted
socket.socket.of('game').emit('updateGameList', hostedGames);
};
,这样你们可以看到,当用户点击加入游戏时,它把对手的id这就是托管他们想加入游戏。如果我做user.emit它会去加入的人,如果我做em.emit它会去每个用户在网站上。我将如何将它引导到该特定ID的用户?
你为什么要标记的Java? –
MB我打字太快,意味着JavaScript的 –
你有另一座专门为短信? – Mike