web-dev-qa-db-ja.com

Node.jsおよびSocket.ioの作成ルーム

あなたの助けを求めることができます。 socket.roomを使用してルームを作成する場合、私のコードは機能しません。最初にvar rooms = ['Lobby'];を宣言し、ルームを作成して、作成したルーム名をrooms[]にプッシュします。私の目標は、ユーザーが自分の部屋を作成し、可能であれば削除できるようにすることです。参照としてMichael Mukhin here のコードを使用しました。

これが私のserver.jsのコードです

var redis = require('redis');
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var publish = redis.createClient();
var subscribe = redis.createClient();

server.listen(8080);


app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

var usernames = {};

var rooms = ['Lobby'];

io.sockets.on('connection', function (socket) {

    socket.on('adduser', function (username){
        socket.username = username;
        socket.room = 'Lobby';         
        usernames[username] = username;
        socket.join('Lobby');          
        subscribe.subscribe(socket.room);   
        socket.emit('updatechat', 'SERVER', 'you have connected to Lobby');
        socket.broadcast.to('Lobby').emit('updatechat', 'SERVER', username + ' has connected to this room');
        socket.emit('updaterooms', rooms, 'Lobby');
    });

    socket.on('create', function (room) {
        var room = 'test';
        rooms.Push(room);
        });

    socket.on('sendchat', function (data) {

        io.sockets.in(socket.room).emit('updatechat', socket.username, data);
        if (socket.room === 'Lobby') {
            publish.publish('Lobby', data);
        } else {
        publish.publish(socket.room, data);
        }
    });

    socket.on('switchRoom', function(newroom){
        socket.leave(socket.room);
        socket.join(newroom);
        subscribe.subscribe(newroom);
        socket.emit('updatechat', 'SERVER', 'you have connected to '+ newroom);
        socket.broadcast.to(socket.room).emit('updatechat', 'SERVER', socket.username+' has left this room');
        socket.room = newroom;
        socket.broadcast.to(newroom).emit('updatechat', 'SERVER', socket.username+' has joined this room');
        socket.emit('updaterooms', rooms, newroom);
    });



    socket.on('disconnect', function(){

        delete usernames[socket.username];
        io.sockets.emit('updateusers', usernames);
        socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
        socket.leave(socket.room);
    });
});

これはクライアントのindex.htmlのコードです。ルームを作成し、rooms[]のリストに追加したいと思います。

<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
    var socket = io.connect('http://localhost:8080');


    socket.on('connect', function(){

        socket.emit('adduser', Prompt("What's your name: "));
        test();
    });


        //this is my create room to be called when i click a button
        socket.on('createroom', function () {
            socket.emit('create', room);
        });




    socket.on('updatechat', function (username, data) {
        $('#conversation').append('<b>'+ username + ':</b> ' + data + '<br>');
    });


    socket.on('updaterooms', function (rooms, current_room) {
        $('#rooms').empty();
        $.each(rooms, function(key, value) {
            if(value == current_room){
                $('#rooms').append('<div>' + value + '</div>');
            }
            else {
                $('#rooms').append('<div><a href="#" onclick="switchRoom(\''+value+'\')">' + value + '</a></div>');
            }
        });
    });

    function switchRoom(room){
        socket.emit('switchRoom', room);
    }


    $(function(){
        $('#datasend').click( function() {
            var message = $('#data').val();
            $('#data').val('');
            socket.emit('sendchat', message);
        });


        $('#data').keypress(function(e) {
            if(e.which == 13) {
                $(this).blur();
                $('#datasend').focus().click();
            }
        });
    });

</script>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
    <b>ROOMS</b>
    <div id="rooms"></div>
</div>

<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
    <div id="conversation"></div>
    <input id="data" style="width:200px;" />
    <input type="button" id="datasend" value="send" />
</div>

すでにsocket.ioのドキュメントを読んだ人たちを助けてください。しかし、理解するのは難しいと感じました。あなたが私を助けてくれることを願っています。事前に感謝します、すみませんが、まだsocket.ioとnode.jsを学んでいます。ありがとう。

15
Joenel de Asis

これは役立つかもしれません:

server.js(redisに関するコードなし)

var usernames = {};

var rooms = ['Lobby'];

io.sockets.on('connection', function(socket) {
    socket.on('adduser', function(username) {
        socket.username = username;
        socket.room = 'Lobby';
        usernames[username] = username;
        socket.join('Lobby');
        socket.emit('updatechat', 'SERVER', 'you have connected to Lobby');
        socket.broadcast.to('Lobby').emit('updatechat', 'SERVER', username + ' has connected to this room');
        socket.emit('updaterooms', rooms, 'Lobby');
    });

    socket.on('create', function(room) {
        rooms.Push(room);
        socket.emit('updaterooms', rooms, socket.room);
    });

    socket.on('sendchat', function(data) {
        io.sockets["in"](socket.room).emit('updatechat', socket.username, data);
    });

    socket.on('switchRoom', function(newroom) {
        var oldroom;
        oldroom = socket.room;
        socket.leave(socket.room);
        socket.join(newroom);
        socket.emit('updatechat', 'SERVER', 'you have connected to ' + newroom);
        socket.broadcast.to(oldroom).emit('updatechat', 'SERVER', socket.username + ' has left this room');
        socket.room = newroom;
        socket.broadcast.to(newroom).emit('updatechat', 'SERVER', socket.username + ' has joined this room');
        socket.emit('updaterooms', rooms, newroom);
    });

    socket.on('disconnect', function() {
        delete usernames[socket.username];
        io.sockets.emit('updateusers', usernames);
        socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
        socket.leave(socket.room);
    });
 });

index.html

<head>
... // your other code
<script>
var socket = io.connect('http://localhost:8000');

socket.on('connect', function(){
    socket.emit('adduser', Prompt("What's your name: "));
});

socket.on('updatechat', function (username, data) {
    $('#conversation').append('<b>'+ username + ':</b> ' + data + '<br>');
});


socket.on('updaterooms', function (rooms, current_room) {
    $('#rooms').empty();
    $.each(rooms, function(key, value) {
        if(value == current_room){
            $('#rooms').append('<div>' + value + '</div>');
        }
        else {
            $('#rooms').append('<div><a href="#" onclick="switchRoom(\''+value+'\')">' + value + '</a></div>');
        }
    });
});

function switchRoom(room){
    socket.emit('switchRoom', room);
}

$(function(){
    $('#datasend').click( function() {
        var message = $('#data').val();
        $('#data').val('');
        socket.emit('sendchat', message);
    });

    $('#data').keypress(function(e) {
        if(e.which == 13) {
            $(this).blur();
            $('#datasend').focus().click();
        }
    });

    $('#roombutton').click(function(){
        var name = $('#roomname').val();
        $('#roomname').val('');
        socket.emit('create', name)
    });
});

</script>
</head>
<body>
    <div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
        <b>ROOMS</b>
        <div id="rooms"></div>
    </div>

    <div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
        <div id="conversation"></div>
        <input id="data" style="width:200px;" />
        <input type="button" id="datasend" value="send" />
    </div>

   <div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
       <div id="room creation"></div>
       <input id="roomname" style="width:200px;" />
        <input type="button" id="roombutton" value="create room" />
   </div>
   ... // the rest of your page
</body>
33
warchimede