我在我的多人小游戏中使用了socket.io和node.js。我有一系列的用户。
index.html
socket.emit('1st word',$wordInput.val());
server.js
users = [];
//rest of code
socket.on('1st word', function(data){
//here is where i was thinking of doing a circular array
});我想做的是做一个圆形数组。因此,假设有3个用户。用户1发送给用户2,用户2发送给用户3,用户3发送给用户1。我希望它像这样发送3轮(因为用户的长度是3)。
任何建议都会很有帮助!如果你有更多的问题,请询问q's!谢谢
发布于 2017-07-19 11:52:25
也许你可以这样做:
//lets say all the user have different id
//index.html user 1
var user1="abcde1"
//you add user id into the server first using socket.io lets say you emit adduser to server
socket.emit("adduser",{user:user1})
//this will emit back if there is another user
socket.on("emitback",function(data){
socket.emit("adduser",{user:data.user})
})然后在服务器端
//server.js
var user=[]
socket.on("adduser",function(data){
if(user.indexOf(data.user)==-1){
//we add user into array user
user.push(data.user)
}
//if the array already has the id of the user we emit to user 2
else if(user.indexOf(data.user)>-1){
//if user array length is longer than 1 we emit to next user if not we emit to ourselves
if(user.length>1 && user.indexOf(data.user)!=user.length-1){
socket.emit("emitback",{user:user[user.indexOf(data.user)+1]})
}
//this will emit to the first user because this is the last user
else if(user.length>1 && user.indexOf(data.user)==user.length-1){
socket.emit("emitback",{user:user[0]})
}
else if(user.length==1){
socket.emit("emitback",{user:user[user.indexOf(data.user)]})
}
}
})发布于 2017-07-19 13:59:30
套接字不会从一个用户发送到另一个用户,每个用户都会连接到服务器并将其命令发送到服务器。
您必须跟踪您的用户,并在服务器端彼此之间发送命令。
/// Server.js
var users = []
io.sockets.on('connect', (socket) => {
socket.on("joingame", (jgCallback) => {
if (users.length < 3) {
if (users.length > 0) {
users[users.length - 1].nextSocket = socket; // connect this socket to the previous one
}
users.push(socket);
if (users.length === 3) {
socket.nextSocket = users[0]; // connect this socket to the first one
}
jgCallback({ success: true })
}
else {
jgCallback({ success: false })
}
})
socket.on("sendword", (payload, swCallback) => {
if (users.length === 3 && socket.nextSocket) { // There are 3 users, and This socket has a "nextSocket" property
socket.nextSocket.emit("sendword", payload); // send to the neighbor
swCallback({success:true})
}
else {
swCallback({success:false})
}
})
});
/// Clients.js
io.emit("joingame", (jgCallbackResponse) => {
if (jgCallbackResponse.success){
// you are in the game
}
})// Join the game.
io.on("sendword", (payload) => {
// from the previous user in the chain
console.log(payload.word)
})
io.emit("sendword", { word: "my word" }, (swCallbackResponse) => {
if (swCallbackResponse.success){
// word sent
}
});https://stackoverflow.com/questions/45179960
复制相似问题