iT邦幫忙

1

想用Socket.io做同步聊天室

不好意思,小弟是socket.io新手,觀念還有很多不懂的地方,請各位大大多多包涵。想問一下我想要在表單提交資料之後呼叫'joinRoom'。但是怎麼試都不成功...也沒有報錯,而且後面的console.log(req.body) 跟 res.sendFile('public/chat.html', { root: __dirname }) 都有執行,想問各位大大我該如何解決...

<body>
    <form action="chat" id="main" method="post">
        <div>
            <input type="text" id="id" name="username" value="" placeholder=" " required />
            <label for="id">暱稱</label>
        </div>
        <div>
            <input type="text" id="key" name="key" value="" placeholder=" " />
            <label for="key">房號</label>
        </div>
        <button type="submit" value="加入房間" class="btn">加入房間</button>
    </form>

</body>
io.on('connection', (socket) => {

    socket.on('joinRoom', username => {
        console.log(username);
        console.log("joinRoom");
    });
    socket.on('chat message', msg => {
        const user = getCurrentUser(socket.id);
        console.log(user);
        io.emit('chat message',  msg);
  });
});
app.post('/chat', urlencodedParser, function (req, res) {
    io.sockets.emit('joinRoom', "aa")
    console.log(req.body)
    res.sendFile('public/chat.html', { root: __dirname })
});
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
fillano
iT邦超人 1 級 ‧ 2021-12-09 16:47:19

https://socket.io/get-started/chat

先看一下官方範例,你的觀念不太對。

fillano iT邦超人 1 級 ‧ 2021-12-09 17:22:30 檢舉

client有程式嗎?沒看到東西。

socket.io最主要的使用方法是,在server端用on定義的事件,可以在client端用emit觸發,然後在client端用on定義的事件,可以在server端用emit觸發。然後就是這樣子互傳訊息。

你寫的那個joinRoom定義在server,在server emit沒用的。而且你透過sockets.emit(),這樣應該是一個廣播訊息了。

你把範例跑一跑,然後根據需要改改看。

我要發表回答

立即登入回答