실시간, 양방향 및 지속적인 연결 가능
짧은 지연 시간의 데이터 교환
실시간 채팅이나 게임에 적합
Polling, Streaming 기술을 대체
HTML5 표준 기술로 최신 브라우저의 경우 웹소켓을 지우너함
미지원 브라우저도 존재한다 (이런 경우에는 WebSocket Emulation으로 대체 할 수 있다 <socket.io, SockJS>) - 호환성 문제 해결 가능
클라이언트와 서버 간의 연결은 둘 중 하나에 의해 종료되거나 시간 초과에 의해 닫힐 때까지 열린 상태로 유지됨
- 연결이 종료될때까지 동일한 채널을 사용하여 통신이 수행됨
웹소켓 통신은 실시간 데이터 업데이트와 클라이언트 메시지를 보내는 기능이 필요할 때 주로 사용됨
Node.js & Express.js 활용
웹소켓 통신을 주고 받을 서버와 클라이언트가 있어야 함. 이를 위해 간단하고 빠르게 서버를 구현할 수 있는 Node.js와 Express.js 프레임워크를 사용할 수 있음
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")
}
</script>
</head>
<body>
<h1>Websocket 실습 과제</h1>
<button onclick="sendMsg()">전송</button>
</body>
</html>
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 => {
ws.on("message", data => {
console.log(`Received from client: ${data}`)
})
})
** 참고