我最近开始使用 socket.io,并且开始掌握它的窍门。但一夜之间有些东西坏了,我不明白为什么。 当我调用socket.id(在socket.on中)时,我得到了未定义。但在其他 socket.on 函数中它工作正常。
谁能解释一下为什么它突然停止工作了?下面是我的代码。
这是我的 App.js:
socket.on('selectedcard', function(data){
// if(localStorage.getItem("legstapel" != null)){
// var legstapel = localStorage.getItem("legstapel");
// }
// else{
// var legstapel = [];
// }
var legstapel = GAME_LIST[1].legstapel;
//console.log(PLAYER_LIST[socket.id].hand[data.card]);
console.log("SOCKET: ", socket.id); //this returns undefined
console.log("SOCKET: ", SOCKET_LIST[socket.id].id); //and therefor this line throws an undefined error
var infonext = dealnodeal(GAME_LIST[1].topstapel, PLAYER_LIST[socket.id].hand[data.card]);
if(infonext[2] == true){
socket.emit('Boerchoice');
}
if(infonext[0] == true && infonext[1] == true){
currentturn = nextplayer(currentturn);
}
else if (infonext[0] == true && infonext[1] == false) {
goAgain();
}
else{
socket.emit('wrong');
}
if(infonext[0] == true){
legstapel.push(PLAYER_LIST[socket.id].hand[data.card]); //this is where i need socket.id to work.
console.log(legstapel)
GAME_LIST[1].topstapel = PLAYER_LIST[socket.id].hand[data.card];
GAME_LIST[1].legstapel = legstapel;
};
console.log("topstackchange " + GAME_LIST[1].topstapel);
//for(var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
socket.emit("topstackchange", {
topstapel: GAME_LIST[1].topstapel
});
//};
});
这是客户端:
PickCard = function(Cname){
var turn = localStorage.getItem('turn')
console.log(turn);
if(turn == '1'){
console.log("card selected : " + Cname);
socket.emit('selectedcard', {
card: Cname
});
}
else{
console.log("Het is niet jouw beurt!");
}
};
编辑: 这是简化的代码:
io.on('connect', function(socket){
var player = Player(socket.id);
SOCKET_LIST[socket.id] = socket;
PLAYER_LIST[socket.id] = player;
socket.on('selectedcard', function(data){
console.log(socket.id); //this is undefined
});
});
最佳答案
所以我认为问题是您在使用 socket
模块连接后没有使用 socket
变量。
io.on('connect', function (socket) {
//this socket refers to the local socket variable which has ID
socket.on('someEvent', function () {
//socket.id will be available here.
})
})
编辑:由于 OP 在使用这段代码时遇到问题,我附上 POC 以供引用。
服务器.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(8080);
io.on('connection', function (socket) {
socket.on('selectedcard', function (data) {
console.log(socket.id); // this is working
console.log(data);
});
});
client.js(使用 Node 进行快速原型(prototype)设计)
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080');
socket.emit('selectedcard', {hey:'yaya'});
结果:
$ node server.js
U9GFjoTEzOsv0hmoAAAA
{ hey: 'yaya' }
关于javascript - 我无法访问服务器端的 socket.io?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51672337/