WebSocket을 사용한 채팅 앱: 브로드캐스트 메시지
                                            
                                                
                                                
                                                
                                                
                                                
                                                 15363 단어  javascriptnodereactwebdev
                    
 
    목차
Sokhavuth TIN ・ 8월 19일 ・ 1분 읽기
GitHub: https://github.com/Sokhavuth/chat
헤로쿠: https://khmerweb-chat.herokuapp.com/
우리는 이미 모든 소켓 클라이언트가 소켓 서버에 채팅 메시지를 보낼 수 있다는 것을 알고 있습니다. 반대로 소켓 서버는 모든 소켓 클라이언트에게 채팅 메시지를 다시 보내거나 전달할 수도 있습니다. 이 사실을 모든 소켓 클라이언트에게 "브로드캐스팅 메시지"라고 합니다.
소켓 서버가 채팅 메시지를 방송할 때 소켓 클라이언트는 많은 키-값 쌍이 있는 ES6 객체일 수 있는 메시지를 수신하기 위해 "채팅 메시지"이벤트에 이벤트 핸들러를 정의해야 합니다.
// index.js
// npm install express
// npm install socket.io
// npm install nodemon
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const path = require('path');
const { Server } = require("socket.io");
const io = new Server(server);
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
    res.sendFile(`${__dirname}/index.html`);
});
io.on('connection', (socket) => {
    console.log('a user connected');
    socket.on('chat message', (obj) => {
        io.emit('chat message', obj);
    });
});
server.listen(port, () => {
    console.log(`listening on *${port}`);
});
<!--index.html-->
<!DOCTYPE html>
<html>
  <head>
    <title>Khmer Web Chat</title>
    <link rel="stylesheet" href="/base.css" />
    <link rel="stylesheet" href="/chat.css" />
    <link href="/fonts/setup.css" rel="stylesheet" />
    <link href="/logo.png" rel="icon" />
  </head>
  <body>
    <section class="Chat region">
        <div class="main">
            <div class="title">
                <input type="button" value="Leave chat" />
            </div>
            <div class="outer">
                <div id="msg-board"></div>
                <form action="" onSubmit="submitHandler(event)">
                    <input type="text" id="chat-name" 
                    required placeholder="Chat name" />
                    <input id="input" autocomplete="off" required 
                    placeholder="Type your message here" />
                    <input type="submit" value="Send" />
                </form>
            </div>
        </div>
        <div class="sidebar">
            <div class="title">All people</div>
            <div class="content">Users</div>
        </div>
    </section>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        const socket = io();
        function submitHandler(e){
            e.preventDefault();
            const chatName = document.getElementById('chat-name');
            const input = document.getElementById('input');
            const obj = {
                chatName: chatName.value, 
                message: input.value,
            };
            if (input.value) {
                socket.emit('chat message', obj);
                input.value = '';
            }
        }
        socket.on('chat message', function(obj){
            const msgBoard = document.getElementById('msg-board');
            const element = document.createElement('div');
            const msg = `${obj.chatName}: ${obj.message}`;
            element.textContent = msg;
            msgBoard.appendChild(element);
            window.scrollTo(0, document.body.scrollHeight);
        });
    </script>
  </body>
</html>
Reference
이 문제에 관하여(WebSocket을 사용한 채팅 앱: 브로드캐스트 메시지), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/sokhavuth/chat-app-with-websocket-broadcasting-message-hnb텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)