본문 바로가기
CS

웹소켓 구현해보기 2편 - 클라이언트와 서버 연결 (Web Socket with Node.js)

by 김무스비 2025. 1. 25.
728x90
반응형

지난 1편에서는 웹소켓 서버를 생성해봤는데요.

이번에는 생성한 웹소켓 서버(백엔드)와 클라이언트(프론트엔드)를 연결해보려고 합니다.

1편은 아래 링크를 참고해주세요!

https://musubi-iroiro.tistory.com/461

 

웹소켓 구현해보기 1편 - 웹소켓의 정의와 웹소켓 서버 생성 (Web Socket with Node.js)

웹소켓의 정의웹소켓(WebSocket)은 HTML5에서 소개된 통신 프로토콜로, 클라이언트와 서버(브라우저와 서버)를 연결하고 실시간으로 통신이 가능하도록 하는 프로토콜입니다. http처럼 이것도 프로

musubi-iroiro.tistory.com


서버와 클라이언트 연결하기

웹소켓 서버를 만들었다면, 클라이언트와 연결을 해봅시다.

우선, 백엔드 쪽에서는 새로운 클라이언트가 연결되었을 때 어떤 처리를 해줄 지 정의해줍시다.

//WebSocket 서버는 새로운 클라이언트가 연결되면 "connection" 이벤트를 발생
wss.on("connection", 
  (socket) => {  		//connection 이벤트 발생할 때 실행해줄 콜백함수
  console.log(socket);  //함수에 연결된 소켓 객체(socket)를 자동으로 전달
});

이 과정을 흐름대로 정리해보면 다음과 같습니다.

 

  1. 클라이언트가 ws:// 또는 wss:// 프로토콜을 통해 서버에 연결 요청을 보냅니다.
  2. 서버는 이를 수락하며, 서버는 내부적으로 클라이언트와의 연결을 나타내는 새로운 WebSocket 객체를 생성합니다.
  3. WebSocket 서버는 "connection" 이벤트를 발생시키고, 이벤트 핸들러(wss.on의 두번째 인자)로 소켓을 전달
  4. 이벤트 핸들러 함수는 소켓 객체를 매개변수로 받아서 출력해줍니다.(여기서 socket 객체는 연결된 브라우저=클라이언트입니다.)

 

이제 프론트쪽에서 접근을 시도해봅시다.

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

 

이제 기존에 만든 localhost 포트를 새로고침 하게 되면, 

 

vscode 터미널 창에 다음과 같이 뜨게 됩니다. server.js에서 로그를 찍어주는 것이므로 브라우저의 콘솔이 아니라 vscode의 터미널 창에 결과가 뜨는게 맞습니다. 

 

서버와 클라이언트가 데이터 주고받기

1. 서버 → 클라이언트

연결은 잘 된 것 같으니, 서버와 클라이언트가 서로 데이터를 주고 받아 볼까요?

우선 서버에서 클라이언트로 메세지를 보내보겠습니다.

위에서 작성한 wss.on 메서드를 다음과 같이 수정해줍시다.

//server.js
wss.on("connection", (socket) => {
  socket.send("A postcard from web socket server");
});

연결된 클라이언트에게 "A postcard from web socket server" 라는 메시지를 "send" 하겠다는 뜻입니다.

 

이제 프론트에서는 이걸 받아서 출력해봅시다.

//app.js
const socket = new WebSocket(`ws://${window.location.host}`);
socket.addEventListener("message", (message) => {
  console.log(message.data);
});

서버와 연결된 socket 객체에 message 객체의 data속성 값을 출력하는 eventlistener를 add 해줍시다.

 

그러면 웹 브라우저 콘솔창에 다음과 같이 뜨게 됩니다. 이건 vscode의 터미널 창이 아닌 웹 브라우저에 뜨는 것이 맞습니다.

 

2. 클라이언트 → 서버

이제 클라이언트에서 메시지를 보내봅시다. app.js를 다음과 같이 입력해봅시다.

//app.js
const socket = new WebSocket(`ws://${window.location.host}`);
socket.addEventListener("message", (message) => {
  console.log(message.data);
});
setTimeout(() => {
  socket.send("A postcard from client");
}, 5000);

연결되고 5초 후에 소켓(서버)로 "A postcard from client"를 보내겠다는 의미입니다.

 

서버 측에서 받은 메시지를 어떻게 할 건지에 대한 부분도 작업해줘야겠죠? 이제 server.js로 갑시다.

//server.js
wss.on("connection", (socket) => {
  socket.send("A postcard from web socket server");
  socket.on("message", (message) => {
    console.log(message.toString("utf8"));
  });
});

socket.on 함수는 클라이언트가 서버로 보낸 메시지를 수신하며, 해당 메시지를 처리하는 콜백 함수입니다. 서버가 아닌 연결된 개별 브라우저(소켓)에 send, on 메서드를 붙여야하는 점 유의하세욧!

 

정상적으로 실행이 되면, 웹 브라우저가 아닌 터미널에 다음과 같은 로그가 뜨게 됩니다.

그럼 정상적으로 수신 완료!


전체 코드입니다

//views/home.pug
doctype html
html(lang="en")
  head
    meta(charset="UTF-8")
    meta(name="viewport", content="width=device-width, initial-scale=1.0")
    title Hello!
    link(rel="stylesheet" href="https://unpkg.com/mvp.css")
  body 
    header
      h1 Hello!
    script(src="/public/js/app.js")
    
    
    //server.js
    mport express from "express";
import http from "http";
import { WebSocketServer } from "ws";
const app = express();
app.engine("pug", require("pug").__express); //이거 뭐지?
app.set("view engine", "pug");
app.set("views", __dirname + "/views");
app.use("/public", express.static(__dirname + "/public"));
app.get("/", (req, res) => res.render("home"));
app.get("/*", (req, res) => res.redirect("/"));
const handleListen = () => console.log("listening to port 8000");
// app.listen(8000);
const server = http.createServer(app); //이건 http 서버
const wss = new WebSocketServer({ server }); //거기다가 websocket 얹기기

wss.on("connection", (socket) => {
  socket.send("A postcard from web socket server");
  socket.on("message", (message) => {
    console.log(message.toString("utf8"));
  });
});


//public/js/app.js
const socket = new WebSocket(`ws://${window.location.host}`);
socket.addEventListener("message", (message) => {
  console.log(message.data);
});
setTimeout(() => {
  socket.send("A postcard from client");
}, 5000);
728x90
반응형