我有一個使用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