socket.io房间不工作

时间:2017-01-31 11:31:14

标签: javascript node.js socket.io

我是节点js上的socket.io,我的目标是将创建空间和连接房间事件发送到服务器,然后向加入房间的人广播。我成功地创造了我认为的房间,但是当我用.to()发送任何东西时,它都无法工作。

的index.html

<html>

<head>
    <script src="/socket.io/socket.io.js"></script>
</head>

<body>
    <label for="joinRoom"> Join room</label>
    <form id="joinRoom">
        <input id="room" /><button>Send</button>
    </form>
    <label for="createRoom"> Create room</label>
    <form id="createRoom">
        <input id="players" /><button>Send</button>
    </form>
    <script src="/client.js"></script>
</body>

</html>

client.js

const socket = io();

socket.on('test', (data) => console.log(data));

document.getElementById('joinRoom').onsubmit = () => {
    socket.emit('joinRoom', document.getElementById('room').val());
    return false;
};

socket.on('roomCreated', (id) => {
    console.log(id);
    //
});

document.getElementById('createRoom').onsubmit = () => {
    socket.emit('createRoom', document.getElementById('players').value);
    return false;
};

server.js

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);

app.use(express.static('public'));

server.listen(3000, () => {
    console.log('listening...');
});

let currentRoomID = 0;
const rooms = [];

io.on('connection', (socket) => {
    function joinRoom(room) {
        socket.join(room.toString());
    }
    socket.on('createRoom', () => {
        const roomID = currentRoomID++;
        rooms[roomID] = `foo ${roomID}`;
        joinRoom(roomID, socket.id);
        io.sockets.emit('roomCreated', roomID);
        socket.to(roomID.toString()).emit('test', rooms[roomID]);
    });
    socket.on('joinRoom', (room) => {
        joinRoom(room, socket.id);
    });
});

1 个答案:

答案 0 :(得分:1)

如果您想向特定房间的人发出特定消息,请执行以下操作:

io.sockets.in(room).emit('something', something);

或者,如果您想要向特定套接字发送内容,您可以执行以下操作:

io.to(socket).emit('something', something);