WebSocket이 뭘까?

LeeJaeHoon·2022년 3월 31일
0
post-thumbnail

WebSocket

http

  • 유저 requset 서버 response

WebSocket

  • 유저와 서버가 연결된다.
  • 연결돼있기 때문에 서버는 네가 누구인지 기억할 수 있다.
  • 연결돼있기 때문에, 원한다면 request없이 서버가 유저에게 메세지를 보낼 수 있다.
  • 이 모든것은 connection일때만 발생한다.

ws 라이브러리

설치

npm i ws

사용

import http from "http";
import express from "express";
import WebSocket from "ws";
...

const handleListen = () =>
  console.log(`Listening on http://localhost:${Port}`);

// http에
// 동일한 포트에서 http,ws request 두 개를 다 처리할 수 있다.
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

server.listen(Port, handleListen);

new WebSocket.Server({ server }) 이런식으로 해줘야 http 프로토콜과 ws 프로토콜을 동시에 처리할 수 있습니다.

connection

server

wss.on("connection", socket => {
  console.log(socket);
});

“connection”의 뜻은 누군가가 우리의 서버와 연결했다는 의미입니다.

누군가가 서버와 연결되면 두번째인자로 넘겨준 함수가 실행됩니다.

해당 함수는 socket이라는 인자를 받습니다.

front

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

WebSocket은 protocol로 ws나 wss를 쓰므로 서버 url앞쪽에 http가 아닌 ws를 적어줘야 합니다.

이런식으로 해주면 서버와 브라우저는 connection이 이루어집니다.

이때 서버의 connection이벤트가 일어납니다.

서버와 프론트 메세지 주고받기

open

프론트에 다음과 같이 코드를 작성해 봅시다

const socket = new WebSocket(`ws://${window.location.host}`);
socket.addEventListener("open", () => {
  console.log("Connected to Server ✅");
});

open이벤트는 서버와 연결이 되었을때 실행되는 이벤트 입니다.

message

서버에서 다음과 같이 코드를 작성해 봅시다.

wss.on("connection", socket => {
  console.log("Connected to Browser ✅");
  socket.send("Hello!!");
});

socket.send를 통해 프론트로 메세지를 보낼 수 있습니다.

그러면 보낸 메세지를 프론트에서 어떻게 받을 수 있을까요??

바로 “message”이벤트를 통해 서버로부터 온 메세지를 받을 수 있습니다.

const socket = new WebSocket(`ws://${window.location.host}`);
socket.addEventListener("open", () => {
  console.log("Connected to Server ✅");
});
socket.addEventListener("message", message => {
  console.log(message);
});

console.log(message)

위 이미지에서 알수 있듯이 message.data를 통해 서버에서 보낸 data의 내용을 확인 할 수 있습니다.

그러면 브라우저에서 서버로는 어떻게 메세지를 보낼 수 있을까요?

서버와 동일하게 send메서드를 사용하면 됩니다.

setTimeout(() => {
  socket.send("hello from the browser!");
}, 10000);

서버에서도 동일하게 브라우저에서 보낸 메세지를 받을려면 “message”이벤트를 사용하면 됩니다.

wss.on("connection", socket => {
  console.log("Connected to Browser ✅");
  socket.on("message", message => {
    console.log(message);
  });
  socket.send("Hello!!");
});

close

close이벤트는 연결이 끊겼을때 발생하는 이벤트입니다.

const socket = new WebSocket(`ws://${window.location.host}`);
socket.addEventListener("close", () => {
  console.log("Connected to Server ❌");
});

다음과 같이 코드 작성 후 서버를 끄면 해당 이벤트가 발생합니다.

서버에서도 동일하게 close이벤트를 사용할 수 있습니다.

wss.on("connection", socket => {
  console.log("Connected to Browser ✅");
  socket.on("close", () => console.log("DisConnected to Browser ❌"));
  socket.on("message", message => {
    console.log(message);
  });
  socket.send("Hello!!");
});

서버와 브라우저가 연결된 상태에서 브라우저를 끄면 서버에서 close이벤트가 발생합니다.

0개의 댓글