简体   繁体   English

无法发射到特定的房间和客户端(Socket.io 2.0.2)

[英]Unable to emit to a specific room and client (Socket.io 2.0.2)

I am using Socket.io to create a multiplayer game. 我正在使用Socket.io创建多人游戏。 I have used a generated numerical code to dynamically create and join rooms. 我使用了生成的数字代码来动态创建和加入房间。

My issue comes about emitting to specific rooms or even specific clients. 我的问题涉及到特定房间甚至特定客户。 I am unable to emit to a room ( io.in(room).emit('event') or io.to(room).emit('event') They are synonyms ). 我无法发送到房间( io.in(room).emit('event')io.to(room).emit('event') 它们是同义词 )。 I am however able to socket.emit('event') between the server and client just fine. 但是我可以在服务器和客户端之间进行socket.emit('event')正常工作。 No errors. 没有错误。 Simply nothing happens when I use anything but socket.emit() , io.emit() , and socket.on('',function(){ this.emit(); }) . 当我使用socket.emit()io.emit()socket.on('',function(){ this.emit(); })时,什么都不会发生。

The reason I have to emit to specific rooms is to update all clients in their rooms when a new client has joined. 我必须进入特定房间的原因是当新客户加入时更新其房间中的所有客户。 (I had tried emitting to each socket.id in each room but that does not work) . (我曾尝试向每个房间的每个socket.id发出信号,但这不起作用)

browser debugger tracking server emitted events 浏览器调试器跟踪服务器发出的事件

I have uploaded all the code I have used in my Node.js server in hopes that someone can see the error in my program. 我上载了我在Node.js服务器中使用过的所有代码,希望有人能在我的程序中看到错误。 I am new to Socket.io and I am not sure about the validity of how I have set up my dynamic rooms. 我是Socket.io的新手,我不确定如何设置动态会议室。

The room event that does not work is: connectToRoom 不起作用的房间事件是: connectToRoom

Server 服务器

 var express = require('express');
 var app = express();
 var http = require('http').Server(app);
 var io = require('socket.io')(http);

 app.get('/',function(req, res) {
     res.sendFile(__dirname + '/client/index.html');
 });
 app.use('/client',express.static(__dirname + '/client'));
 http.listen(3000, function(){
     console.log('listening on localhost:3000');
 });

io.on('connection', function(socket){
    socket.id = Math.random();
    SOCKET_LIST[socket.id]=socket;

    socket.on('create',function(){
        var thisGameId = ( Math.random() * 100000 ) | 0;
        roomNo+=1;
        roomArr[thisGameId]=thisGameId;
        this.emit('createResponse', {gameId: thisGameId, mySocketId: socket.id});
        this.join(thisGameId.toString());
    });

    socket.on('joinRoom',function(data){
        //playerJoinGame(data);
        //io.sockets.in(data.roomKey.toString()).emit('connectToRoom', "You are in room no. "+data.roomKey);
        //socket.to(data.roomKey.toString()).emit('connectToRoom', "You are in room no. "+data.roomKey);
        if( io.nsps['/'].adapter.rooms[data.roomKey]!== undefined ){
            socket.join(data.roomKey.toString());
            SOCKET_LIST[socket.id].username = data.username;
            this.emit('joinRoomResponse',{
                roomKey:data.roomKey
            });
        }
        if(io.nsps['/'].adapter.rooms[data.roomKey]=== undefined){
            this.emit('joinError',{
                message: "This room does not exist."
            });
        }
    });
    socket.on('updateRoom',function(data){
        var clients=io.sockets.adapter.rooms[data.roomKey].sockets;
        var clientsArr=Object.keys(clients);
        for (var clientId in clientsArr ) {
            io.sockets.connected[clientsArr[clientId]].emit('connectToRoom', {
                roomKey:data.roomKey,
                username:data.username
            });
        }

        io.sockets.in(data.roomKey).emit('connectToRoom', {
            roomKey:data.roomKey,
            username:data.username
        });
    });

    socket.on('disconnect',function(){
    delete SOCKET_LIST[socket.id];
    });
});

Client 客户

var socket = io();
var roomKey,username,mySocketId;    
var optionDiv = document.getElementById('optionDiv');
var optionDivCreate = document.getElementById('optionDiv-create');
var optionDivJoin = document.getElementById('optionDiv-join');

var prepDiv = document.getElementById('prepDiv');
var createDiv = document.getElementById('create-Div');
var lobbyDiv = document.getElementById('lobbyDiv');
var createRoomKey = document.getElementById('create-roomKey');
var createPlayers = document.getElementById('create-players');
var joinForm = document.getElementById('join-form');
var joinForm_roomKey = document.getElementById('join-roomKey');
var joinForm_username = document.getElementById('join-username');
var joinForm_submit = document.getElementById('join-form-submit');
var gameDiv = document.getElementById("gameDiv");

optionDivCreate.onclick=function(){
    socket.emit('create');
};
optionDivJoin.onclick=function(){
    optionDiv.style.display='none';
    prepDiv.style.display='inline-block';
    joinForm.style.display='inline-block';
};
socket.on('createResponse',function(data){
    roomKey = data.gameId;
    mySocketId = data.mySocketId;
    optionDiv.style.display='none';
    prepDiv.style.display='inline-block';
    createDiv.style.display='inline-block';
    createRoomKey.innerHTML = roomKey;
});

joinForm_submit.onclick= function(){

};
joinForm.onsubmit = function(e){
    e.preventDefault();
    roomKey = joinForm_roomKey.value;
    username = joinForm_username.value;
    socket.emit('joinRoom',{
        roomKey:roomKey,
        username:username
    });
    joinForm_roomKey.value='';
    joinForm_username.value='';
};
socket.on('joinRoomResponse',function(data){
    optionDiv.style.display='none';
    createDiv.style.display='none';
    prepDiv.style.display='none';
    lobbyDiv.style.display='inline-block';
    socket.emit('updateRoom',{
        roomKey:roomKey,
        username:username
    });
});
socket.on('connectToRoom',function(data){
    socket.emit('debug');
    //createPlayers.innerHTML = "<br />"+data.username;
    alert("triggered");
});
socket.on('joinError',function(data){
    alert(data.message);
});

HTML HTML

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>Prototype</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div id="optionDiv" style="">
            <button id="optionDiv-create">Create Game</button><br />
            <button id="optionDiv-join">Join Game</button>
        </div>
        <div id="prepDiv" style="display:none;">
            <div id="create-Div" style="display:none;">
                Room Key:<br />
                <h1 id="create-roomKey"></h1>
                <h1 id="create-players"></h1>
            </div>
            <form id="join-form" style="display:none;">
                Username:<br />
                <input id="join-username" type="text" style="width:500px"></input><br />
                Room Key:<br />
                <input id="join-roomKey" type="text" style="width:500px"></input><br />
                <button id="join-form-submit">Join</button>
            </form>
        </div>
        <div id="lobbyDiv" style="display:none;">
            You are in room:<br />
            <h1 id="join-roomKey"></h1><br />
            Players in room:<br />
            <h1 id="join-players"></h1>
        </div>
        <div id="gameDiv" style="display:none;">
            <div id="gameDiv-canvas">
                <canvas id="ctx" width="500" height="500" style="border:1px solid #000000;">
                </canvas>
            </div>
            <div id="gameDiv-chat">
                <div id="chat-text" style="width:500px;height:100px;overflow-y:scroll">
                    <div>
                        Hello!
                    </div>
                </div>
                <form id="chat-form">
                    <input id="chat-input" type="text" style="width:500px"></input>
                </form>
            </div>
        </div>
        <!--<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.2/socket.io.js"></script>-->
        <script src="/socket.io/socket.io.js"></script>
        <script src="/client/js/client.js"></script>
    </body>
</html>

正确的语法如下:

io.to('some room').emit('some event');

I have resolved my issue. 我已经解决了我的问题。 The issue in this program is the way that I have made my program. 该程序中的问题是我编写程序的方式。 The program is coded in a "non-dynamic room" manner. 该程序以“非动态房间”的方式编码。 I have coded the program to only handle one game instance. 我已经将该程序编码为仅处理一个游戏实例。 Not multiple game instances for each room. 每个房间没有多个游戏实例。

It is due to the fact that I am using one "game" instance for all the rooms. 这是由于我在所有房间都使用一个“游戏”实例。 All games in each room will be using the same codes. 每个房间中的所有游戏都将使用相同的代码。 Because I am running separate unique game instances for each unique room, I also need to create unique code for each corresponding game instance. 因为我为每个唯一的房间运行单独的唯一游戏实例,所以我还需要为每个对应的游戏实例创建唯一的代码。 This program does not create unique codes for each corresponding game instance. 该程序不会为每个相应的游戏实例创建唯一的代码。 Hence it does not work. 因此,它不起作用。

I have restructured the program in a modular manner to handle activities for each individual room. 我已经以模块化的方式重组了程序,以处理每个房间的活动。

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

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