![](/img/trans.png)
[英]Get array from node.js (server-side)to react app.js (client-side)
[英]Calling a function from server-side on the client-side (Node.js)
我在服務器上有以下代碼:
var game = io.listen(app);
game.sockets.on('connection', function(socket){
storePlayers(socket.id);
//Only the player the connects gets this message
socket.emit('firstTime', {message: 'Welcome!'});
//If a player disconnects, a message will be sent to all the sockets.
socket.on('disconnect', function(){
game.sockets.emit('exit', {message: 'Player ' + socket.id + ' left the game...!'});
});
//When a player connects, all the players will get this message.
game.sockets.emit('entrance', {message: 'Player ' + socket.id + ' is online'});
});
我想保留storePlayers(id)
函數。 原因是當套接字連接時,應該使用客戶端上的特定socket.id
創建對象。
我將如何去做這樣的事情?
據我了解,您希望客戶端在連接到服務器時發送一個id
。可以通過在客戶端連接到服務器后發送一條消息來實現此目的。
客戶端
var socket = io.connect('your_server')
socket.on('connect', function () {
clientId = generate_id(); //however you want to generate the id
socket.emit('newUser', {id: clientId});
}
然后,您可以在服務器上捕獲消息“ newUser”,並檢索已連接客戶端的ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.