简体   繁体   English

套接字IO-Socket.emit发送到所有客户端

[英]Socket IO - Socket.emit is sent to all clients

I am creating a game using socket io. 我正在使用套接字io创建游戏。 A player connects like this: 玩家连接如下:

var playerName = document.getElementById("name").value;
socket.emit('setup player', {
    name : playerName
});

Then on the server, the player is setup and his information is sent back to the client: 然后在服务器上设置播放器,并将其信息发送回客户端:

function onSetupPlayer(data) {
    ...
    var newPlayer = new Player(x, y, color, data.name,
        this.id, scale);
    socket.emit('setup game', {
        localPlayer : newPlayer
    });
    ...
    sockets[this.id] = socket;
}

The following call: 以下调用:

socket.emit('setup game', {
        localPlayer : newPlayer
});

Should send the setup data only back to the client that requested the setup to be done originally. 应该只将设置数据发送回请求原来完成设置的客户端。 However the setup call gets send to everyone in the lobby. 但是,设置呼叫会发送给大厅中的每个人。

Could this have anything to do with the fact that I am using localhost to test it? 这与我使用本地主机进行测试的事实有关吗? I am also testing it on the same machine by using different tabs. 我还通过使用不同的选项卡在同一台计算机上对其进行测试。 If this is what is causing the issue, is there a way to resolve it? 如果这是导致问题的原因,是否有解决方法? Since this is pretty annoying when testing my game. 由于测试我的游戏时这很烦人。

EDIT: Initialization: 编辑:初始化:

var express = require('express');
var app = express();
var http = require('http').Server(app);
var socket = require('socket.io')(http);
var path = require('path');
var io = require('socket.io')(80);
...
var setEventHandlers = function() {
    socket.sockets.on("connection", onSocketConnection);
};

Listening for connection: 监听连接:

function onSocketConnection(client) {
    ...
    client.on("setup player", onSetupPlayer);
    ...
};

And on the client side I have this: 在客户端,我有这个:

var setEventHandlers = function() {
    socket.on("setup game", onSetupGame);
     ...
}

socket.emit send event to everyone excepts this. socket.emit发送事件给所有人, socket.emit To send data back to this user try 要将数据发送回该用户,请尝试

io.to(socket).emit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM