๐Ÿ’ฌNodeJs WebSocketS ์ฑ„ํŒ… ์•ฑ

1878 ๋‹จ์–ด
์ดˆ๊ฐ„๋‹จ ์ฑ„ํŒ… ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์„ ๋งŒ๋“ค๊ณ  ์‹ถ๋‹ค๋ฉด ๋ฌผ๋ก  ์ ˆ๋Œ€ 1์œ„์ธ socket.io๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
ํ”„๋ŸฐํŠธ์—”๋“œ์™€ ๋ฐฑ์—”๋“œ์—์„œ WebSocket API๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.

์›น์†Œ์ผ“ ํด๋ผ์ด์–ธํŠธ



WebSocket ๊ฐœ์ฒด๋Š” ์„œ๋ฒ„์— ๋Œ€ํ•œ WebSocket ์—ฐ๊ฒฐ์„ ๋งŒ๋“ค๊ณ  ๊ด€๋ฆฌํ•˜๊ธฐ ์œ„ํ•œ API๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.
๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ์—ฐ๊ฒฐ์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ์†ก์ˆ˜์‹ ํ•ฉ๋‹ˆ๋‹ค.

ํด๋ผ์ด์–ธํŠธ ์ธก์—์„œ ๋จผ์ € WebSocket ์—ฐ๊ฒฐ์„ ์ƒ์„ฑํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

const socket = new WebSocket('ws://localhost:8080');



์ด๋ฒคํŠธ



addEventListener()๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์„ธ ๊ฐœ์˜ ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ๋ฅผ ์ƒ์„ฑํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
  • ์ฒซ ๋ฒˆ์งธ '์˜คํ”ˆ' ์ด๋ฒคํŠธ,
    WebSocket๊ณผ์˜ ์—ฐ๊ฒฐ์ด ์—ด๋ฆฌ๋ฉด ์‹œ์ž‘๋จ,
  • '๋‹ซ๊ธฐ' ์ด๋ฒคํŠธ์— ๋Œ€ํ•œ ๋‘ ๋ฒˆ์งธ ํ•ญ๋ชฉ
    WebSocket๊ณผ์˜ ์—ฐ๊ฒฐ์ด ๋‹ซํž ๋•Œ ์‹œ์ž‘๋จ,
  • ๋ฐ '๋ฉ”์‹œ์ง€' ์ด๋ฒคํŠธ์˜ ๋งˆ์ง€๋ง‰ ํ•ญ๋ชฉ์ธ
    WebSocket์„ ํ†ตํ•ด ๋ฐ์ดํ„ฐ๋ฅผ ์ˆ˜์‹ ํ•˜๋ฉด ์‹œ์ž‘๋ฉ๋‹ˆ๋‹ค.

  • socket.addEventListener('open', function (event) {
        socket.send('Hello Server!');
    });
    
    socket.addEventListener('message', function (event) {
        console.log('Message from server ', event.data);
    });
    
    


    ์„œ๋ฒ„ ์ธก์˜ WebSocket



    ๋ฐฑ์—”๋“œ์—์„œ๋Š” WebSocket ๊ธฐ์ˆ ์„ ์‚ฌ์šฉํ•  ์ˆ˜๋„ ์žˆ๊ณ  NodeJs์—์„œ๋Š” ์„ค์น˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
    ws library
    ๊ตฌํ˜„ํ•˜๊ธฐ๊ฐ€ ๋งค์šฐ ์‰ฝ์Šต๋‹ˆ๋‹ค. ์„ค์น˜ํ•˜๋ ค๋ฉด ์ด ๋ช…๋ น์„ ์ˆ˜ํ–‰ํ•˜์‹ญ์‹œ์˜ค.

    npm i ws



    WebSocket ์„œ๋ฒ„ 'wss' ๊ฐ€์ ธ์˜ค๊ธฐ ๋ฐ ์ƒ์„ฑ

    import WebSocket, {WebSocketServer} from 'ws';
    
    const wss = new WebSocketServer({port:8080});
    
    


    ์—ฐ๊ฒฐ์„ ์ˆ˜์‹ ํ•˜๊ณ  ๋ฌธ์ž์—ด ๋˜๋Š” ๊ฐœ์ฒด ํ™˜์˜ ๋ฉ”์‹œ์ง€๋ฅผ ๋ณด๋ƒ…๋‹ˆ๋‹ค.

    wss.on('connection', (ws, req)=>{
    
     ws.send(JSON.stringify({time: datetime, message:`๐Ÿ’ฌ Welcome from the Server ๐ŸŽ‰.`}));
    });
    
    


    ์ด ๋น„๋””์˜ค ๊ฐ€์ด๋“œ์—์„œ ๋งค์šฐ ๊ฐ„๋‹จํ•œ ๊ตฌํ˜„์„ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ข‹์€ ํ•˜๋ฃจ ๋˜์„ธ์š”!

    Video Guide
    ๐Ÿ†— ๐Ÿ‘‹

    ์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ