我最近开始使用socket.io,并且开始了解它。但是一夜之间发生了什么事,我不知道为什么。 当我在socket.on中调用socket.id时,我不确定。但在其他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
});
});
答案 0 :(得分:2)
所以我认为问题在于,使用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供参考。
server.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(使用节点进行快速原型制作)
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080');
socket.emit('selectedcard', {hey:'yaya'});
结果:
$ node server.js
U9GFjoTEzOsv0hmoAAAA
{ hey: 'yaya' }
答案 1 :(得分:0)
在提供的代码中,尚不清楚客户端和服务器是否进行了成功的握手-可能不是。您可以在服务器端成功建立连接的套接字实例,并可以与之取得socket.id,例如看到阿里特拉的答案