JavaScript

[JavaScript] WebSocket | ์„œ๋ฒ„์™€ ๋ธŒ๋ผ์šฐ์ € ์—ฐ๊ฒฐ

jjingle 2024. 3. 28. 11:12

1. express ๋กœ ์„œ๋ฒ„ ๊ตฌ์ถ•

  • express ?
    • node.js์˜ ํ”„๋ ˆ์ž„์›Œํฌ
    • ์„œ๋ฒ„ ์‚ฌ์ด๋“œ ํ”„๋ ˆ์ž„์›Œํฌ๋กœ Node.js์˜ API๋ฅผ ๋‹จ์ˆœํ™”ํ•˜๊ณ , ์‰ฝ๊ฒŒ ์„œ๋ฒ„ ๊ตฌ์ถ• ๊ฐ€๋Šฅ
  • express application์œผ๋กœ๋ถ€ํ„ฐ http server ์ƒ์„ฑ
import express from 'express';
import http from 'http';

const app = express();
const server = http.createServer(app);

 

 

2. http ์„œ๋ฒ„ ์œ„์—, webSocket ์„œ๋ฒ„ ๊ตฌ์ถ• -> ๊ฐ™์€ ํฌํŠธ ์ด์šฉ

import ws from 'ws';

//http ์„œ๋ฒ„ ์ „๋‹ฌ
const wss = new we.WebSocketServer({ server });

 

 

3. WebSocket Connection :  ์„œ๋ฒ„ -> ๋ธŒ๋ผ์šฐ์ € ์—ฐ๊ฒฐ

  • socket.on()  : socket์œผ๋กœ๋ถ€ํ„ฐ ์˜จ ์ •๋ณด ์ œ๊ณต
wss.on('connection', socket => {
  console.log('Connected to Browser โœ…');
  socket.on('close', () => console.log('Disconnected from the Browser โŒ'))
  
  socket.on('message', message => {
    console.log(message.toString('utf8'));
  });
  socket.send('Hello!');
});

 

 

4. WebSocket Connection :  ๋ธŒ๋ผ์šฐ์ € -> ์„œ๋ฒ„ ์—ฐ๊ฒฐ

  • socket.addEventListener()
//app.js

const socket = new WebSocket(`ws://${window.location.host}`);

socket.addEventListener('open', () => {
  console.log('Connected to Server โœ…');
});

socket.addEventListener('message', message => {
  console.log('Just got this: ', message.data, ' from the server');
});

socket.addEventListener('close', () => {
  console.log('Disconnected from Server โŒ');
});

setTimeout(() => {
  socket.send('Hello from the Browser!');
}, 10000);

 

 

5. connection ํ™•์ธ

  • server

  • browser

'JavaScript' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[JavaScript] WebSocket vs Socket IO  (1) 2024.03.29
[JavaScript] NodeJS, nodemon, babel | ํ”„๋กœ์ ํŠธ Server Setup  (0) 2024.03.27
[JavaScript] padStart() : String ์ž๋ฆฌ ์ˆ˜  (0) 2024.02.23