백엔드 개발자

WebSocket 프로그래밍 본문

프로그래밍

WebSocket 프로그래밍

임잠탱 2023. 6. 28. 01:01

현재 공부하고 있는 서버-클라이언트 구조는 

 

클라이언트가 요청 -> 서버에서 응답하는 방식이다.

 

그런데 우리가 많이 쓰는 카카오톡을 생각해보면 실시간으로 메시지를 보내고 또 받을 수 있어야 한다.

 

우리가 메시지를 보낸다 == 클라이언트가 서버에 요청한다.

우리가 메시지를 받는다 == 서버가 클라이언트에 보내준다??? NO!!

서버는 클라이언트의 요청에 응답만 할 수 있다.

 

# Polling

그래서 polling으로 일정 시간마다 서버에 계속 요청을 보내서 나한테 온 메시지 있어?

라고 물어볼 수 있다.

 

음..

그런데 실시간으로 바로바로 소통이 가능할까?

3초마다 요청을 한다고 하면 3초전에 받은 메시지를 뒤늦게야 받게 될 수 있다.

 

그래서 우리는 양방향 소통이 가능한 WebSocket 프로그래밍을 사용할 수 있다.

 

# WebSocket

짜잔

 

새로운 유저가 접속하면 서버가 모든 유저들에게 현재 접속 상태를 알려준다.

또 유저가 메시지를 전송하면 서버가 이를 다시 모든 유저들에게 전송해준다.

 

이런식으로 양방향 소통이 가능한 WebSocket 을 간단하게 만들어 볼 수 있다.

 

## 만들어보자.

 

node 설치.

- brew install node

 

프로젝트 생성할 폴더 생성

- mkdir websocket

 

프로젝트로 이동

- cd websocket

 

프로젝트 초기화 & 라이브러리 설치

- npm init

- npm install express

- npm install ws

 

화면을 구성할 폴더 생성 

- mkdir front

- cd front

 

index.html 파일 생성

- touch index.html

 

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Websocket 실습</title>
<script>
const ws = new WebSocket("ws://localhost:8001")
function sendMsg() {
ws.send("Hello")
}

function sendMessage(){
const nickname = document.getElementById("nickname").value
const message = document.getElementById("message").value
const fullMessage = `${nickname}: ${message}`
ws.send(fullMessage)
}
function receiveMessage(event){
const chat = document.createElement("div")
const message = document.createTextNode(event.data)
chat.appendChild(message)

const chatLog = document.getElementById("chat-log")
chatLog.appendChild(chat)
}
ws.onmessage = receiveMessage
</script>
</head>
<body>
<h1>WebSocket 실습 과제</h1>
 
<div>
<input type="text" id="nickname" placeholder="닉네임"
style="width: 50px"/>
<input type="text" id="message" placeholder="메세지"
style="width: 200px"/>
<button onClick="sendMessage()">전송</button>
<div id="chat-log"></div>
</body>
</html>

 

프로그램 최상단으로 이동(현재 front 기준)

- cd .. 

 

index.js 파일 생성

- mkdir index.js

 

const express = require("express")
const { WebSocketServer } = require("ws")
const app = express()

app.use(express.static("front"))

app.listen(8000, () => {
console.log('Server listening on port 8000')
})

const wss = new WebSocketServer({port:8001})

wss.on("connection", (ws, request) =>{
wss.clients.forEach(client => {
client.send(`새로운 유저가 접속했습니다. 현재 유저 ${wss.clients.size} 명`)
})
console.log(`새로운 유저 접속 : ${request.socket.remoteAddress}`)
ws.on("message", data => {
console.log(`Received from client: ${data}`)
wss.clients.forEach(client => {
client.send(data.toString())
})
})

ws.on("close", () => {
wss.clients.forEach(client =>{
client.send(`유저 한명이 떠났습니다. 현재 유저 ${wss.clients.size} 명`)
})
})
})


 

프로젝트 실행

- node index.js

 

=> localhost:8000으로 접속할 수 있다.

 

실행을 하면 처음에 봤던 이러한 화면을 볼 수 있다

끝!!

 

여러 브라우저로 들어가서 메시지를 보내보고, 브라우저를 종료해보면 상태가 변하는 것을 알 수 있다.

'프로그래밍' 카테고리의 다른 글

Git 컨벤션 & Java 코딩 컨벤션  (0) 2023.09.23
Comments