iT邦幫忙

1

Socket.io - 如何將訊息傳給特定的房間

  • 分享至 

  • xImage

目前使用 Socket.io 來做多房間,多人聊天室,但對於 room 的使用非常混亂 /images/emoticon/emoticon06.gif,想請教各位大大

情境:使用者可以自由選擇一間房間然後在該房間內傳送訊息 (明明看起來就很簡單....
當使用者點擊該房間會觸發 JoinRoom 的事件,在 server 端會監聽到這個事件,當成功進到房間後,會回傳一個 emit('JoinedRoom') 通知前端 JoinedRoom 的事件 ,但前端似乎無法接收到,不曉得是哪裡出了問題。

server.js

socket.on('JoinRoom', room => {
    io.sockets.to(room.id).emit('JoinedRoom', '加入了房间', room.id);
});

socket.on('CreateRoom', (room) => {
    socket.join(room.id);
 })

client.js

socket.on('JoinedRoom', (data) => {
  console.log(data) //沒有被觸發
})

我覺得奇怪的是,前端如何知道是哪個 room.id 能被傳送訊息,但看很多範例似乎都沒有說得很清楚。

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

3
dragonH
iT邦超人 5 級 ‧ 2020-06-13 22:50:41
最佳解答

但是好像沒看到你 emit CreateRoom 這個 event

所以就沒 join room

也就沒後面那些 event

我自己測的 code

server.js

const express = require('express');
const app = express();
const router = express.Router();
const { v5: uuid } = require('uuid');

const port = process.env.PORT || 3000;

app.use(express.static('public'));
router.get('/api', (req, res) => {
    res.status(200).send({
        message: 'Hello ithelp',
    });
});

app.use(router);
const server = app.listen(port, () => {
    console.log(`Server is listening on port ${port}`);
});
const io = require('socket.io')(server);
io.on('connect', (socket) => {
    socket.on('join-room', (roomId) => {
        socket.join(roomId);
        socket.emit('join-room-message', `You've join ${roomId} room`);
        io.sockets.to(roomId).emit('room-brocast', `${socket.id} has join this room`);
    });
    socket.on('create-room', () => {
        const roomId = uuid(`${Date.now()}`, uuid.DNS);
        socket.join(roomId);
        socket.emit('join-room-message', `You've join ${roomId} room`);
        io.to(roomId).emit('room-brocast', `${socket.id} has join this room`);
    })
});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src = "https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io.js"></script>
    <title>Document</title>
    <script>
        const params = new URLSearchParams(window.location.search);
        const roomId = params.get('room');
        const socket = io('http://localhost:3000');
        socket.on('connect', function(){
            if (roomId) {
                socket.emit('join-room', roomId);
            } else {
                socket.emit('create-room');
            }
        });
        socket.on('join-room-message', (message) => {
            console.log(message);
        });
        socket.on('room-brocast', (message) => {
            console.log(message);
        });
    </script>
</head>
<body>
    
</body>
</html>

result
IMAGE

我要發表回答

立即登入回答