我在向特定客户端发送数据时遇到问题。
了Serverside
var io = require('socket.io').listen(app.listen(app.get('port')));
io.sockets.on('connection', function (socket) {
socket.on('onHabboConnection', function (data) {
socket.id = data.id;
socket.join(data.id);
io.sockets.in(data.id).emit('onHabboConnected');
});
socket.on('onHabboConnected', function (data) {
console.log("<" + socket.id + "> " + data.username + " has joined the game.");
});
});
客户机侧
var socket = io.connect('http://localhost:3000');
$( document ).ready(function() {
socket.emit('onHabboConnection', { id:'<%= user.id %>' });
});
socket.on('onHabboConnected', function () {
console.log("WORKING" );
socket.emit('onHabboConnected', { username: '<%= user.username %>'});
});
io.sockets.in(data.id).emit('onHabboConnected');
我尝试了所有方法,但它们都会抛出错误。 这个不会抛出错误但不会做任何事情!
答案 0 :(得分:0)
您正在覆盖在客户端生成的唯一标识socket.id
。这就是为什么你在发光,但它不会去任何地方,因为那个客户端不存在:
socket.on('onHabboConnection', function (data) {
//socket.id = data.id; remove this
socket.join(data.id);
io.sockets.in(data.id).emit('onHabboConnected');
});
如果您想更改socket.id
,请在客户端进行更改。