簡體   English   中英

無法發射到特定的房間和客戶端(Socket.io 2.0.2)

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

我正在使用Socket.io創建多人游戲。 我使用了生成的數字代碼來動態創建和加入房間。

我的問題涉及到特定房間甚至特定客戶。 我無法發送到房間( io.in(room).emit('event')io.to(room).emit('event') 它們是同義詞 )。 但是我可以在服務器和客戶端之間進行socket.emit('event')正常工作。 沒有錯誤。 當我使用socket.emit()io.emit()socket.on('',function(){ this.emit(); })時,什么都不會發生。

我必須進入特定房間的原因是當新客戶加入時更新其房間中的所有客戶。 (我曾嘗試向每個房間的每個socket.id發出信號,但這不起作用)

瀏覽器調試器跟蹤服務器發出的事件

我上載了我在Node.js服務器中使用過的所有代碼,希望有人能在我的程序中看到錯誤。 我是Socket.io的新手,我不確定如何設置動態會議室。

不起作用的房間事件是: connectToRoom

服務器

 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];
    });
});

客戶

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

<!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');

我已經解決了我的問題。 該程序中的問題是我編寫程序的方式。 該程序以“非動態房間”的方式編碼。 我已經將該程序編碼為僅處理一個游戲實例。 每個房間沒有多個游戲實例。

這是由於我在所有房間都使用一個“游戲”實例。 每個房間中的所有游戲都將使用相同的代碼。 因為我為每個唯一的房間運行單獨的唯一游戲實例,所以我還需要為每個對應的游戲實例創建唯一的代碼。 該程序不會為每個相應的游戲實例創建唯一的代碼。 因此,它不起作用。

我已經以模塊化的方式重組了程序,以處理每個房間的活動。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM