본문 바로가기

프로그래밍/웹

node js로 웹소켓(websocket) 통신 구현

반응형

ி 웹소켓

 
* 웹소켓은 ws 혹은 wss(secure 버전) 프로토콜을 이용한다.
* HTTP 통신은 요청/응답 시 연결이 바로 끊기지만 ws는 최초 연결 후 계속 연결을 유지한다.
* 서버 하나에 여러 클라이언트가 접근해 지속적으로 데이터를 송수신하는 서비스에 유용하다.
ex) 채팅, 웹 게임, 주식 차트 등..

주식/코인 차트는 실시간으로 정보를 보여줘야하기 때문에 클라이언트가 매번 차트 정보를 요청해야하지만
웹소켓 이용 시 서버에 요청할 필요없이 소켓을 통해 새로운 데이터를 전달받는다.

* http와 ws는 같은 포트를 공유한다.
http://test.com:8001, ws://test.com:8001


* node 서버 소켓 생성
 // ********* app.js 파일 
 
 // HTTP 서버(express) 생성 및 구동 
 
 // 1. express 객체 생성 
 const express = require('express'); 
 const app = express(); 
 
 // 2. "/" 경로 라우팅 처리 
 app.use("/", (req, res)=>{ 
 	res.sendFile('index.html', { root: __dirname }) 
 }); // index.html 파일 응답
 
 // 3. 30002 port에서 서버 구동 
 const HTTPServer = app.listen(30002, ()=>{ 
 console.log("Server is open at port:30002"); 
 });
 
 const wsModule = require('ws'); 
 // 2. WebSocket 서버 생성/구동 
 const webSocketServer = new wsModule.Server( 
     { server: HTTPServer, 
         // WebSocket서버에 연결할 HTTP서버를 지정한다. 
         // port: 30002 // WebSocket연결에 사용할 port를 지정한다(생략시, http서버와 동일한 port 공유 사용) 
     } 
 );
 
 
 // connection(클라이언트 연결) 이벤트 처리 
 webSocketServer.on('connection', (ws, request)=>{ 
 
     // 1) 연결 클라이언트 IP 취득
     const ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress; 
     
     console.log(`새로운 클라이언트[${ip}] 접속`); 
     
     // 2) 클라이언트에게 메시지 전송 
     if(ws.readyState === ws.OPEN){ // 연결 여부 체크 
         ws.send(`클라이언트[${ip}] 접속을 환영합니다 from 서버`); // 데이터 전송 
     } 
     
     // 3) 클라이언트로부터 메시지 수신 이벤트 처리 
     ws.on('message', (msg)=>{ 
         console.log(`클라이언트[${ip}]에게 수신한 메시지 : ${msg}`); 
         ws.send('메시지 잘 받았습니다! from 서버') 
     }) 
     
     // 4) 에러 처러
     ws.on('error', (error)=>{ 
         console.log(`클라이언트[${ip}] 연결 에러발생 : ${error}`); 
     }) 
     
     // 5) 연결 종료 이벤트 처리 
     ws.on('close', ()=>{ 
         console.log(`클라이언트[${ip}] 웹소켓 연결 종료`); 
     }) 
 });


* index.html 클라이언트 소켓 생성
 <!DOCTYPE html> 
 <html lang="ko"> 
 <head> 
 <script> 
 
 window.onload = function() {
 
 	// 1. 웹소켓 클라이언트 객체 생성 
 	const webSocket = new WebSocket("ws://localhost:30002"); 
 
 	// 2. 웹소켓 이벤트 처리 
 	// 2-1) 연결 이벤트 처리 
 	webSocket.onopen = ()=>{ 
 	console.log("웹소켓서버와 연결 성공"); 
 	}; 
 	// 2-2) 메세지 수신 이벤트 처리 
 	webSocket.onmessage = function (event) { 
 	console.log(`서버 웹소켓에게 받은 데이터: ${event.data}`); 
 	} 
 	// 2-3) 연결 종료 이벤트 처리 
 	webSocket.onclose = function(){ console.log("서버 웹소켓 연결 종료"); 
 	} 
 	// 2-4) 에러 발생 이벤트 처리 
 	webSocket.onerror = function(event){ console.log(event) 
 	} 
 	// 3. 버튼 클릭 이벤트 처리 
 	// 3-1) 웹소켓 서버에게 메세지 보내기 
 		let count = 1; 
 		document.getElementById("btn_send").onclick = function(){ if(webSocket.readyState === webSocket.OPEN){  // 연결 상태 확인
 		webSocket.send(`증가하는 숫자를 보냅니다 => ${count}`); // 웹소켓 서버에게 메시지 전송 
 		count++; // 보낼때마다 숫자를 1씩 증가 
 	} else { 
 		alert("연결된 웹소켓 서버가 없습니다."); 
 		} 
 	} 
 
 	// 3-2) 웹소켓 서버와 연결 끊기 
 
 	document.getElementById("btn_close").onclick = function(){ if(webSocket.readyState === webSocket.OPEN){ // 연결 상태 확인
 	webSocket.close(); // 연결 종료 
 	} else { 
 		alert("연결된 웹소켓 서버가 없습니다."); 
 		} 
 	} 
 };
 
 </script>
 
 
 
 <meta charset="UTF-8"> 
 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
 <title>웹소켓</title> 
 </head> 
 
 <body> 
 <h1>웹소켓 테스트</h1> 
 
 <!-- 버튼 2개 생성 --> 
 <button id="btn_send">메시지 전송</button> 
 <button id="btn_close">연결 끊기</button> 
 </body> 
 </html>


http://127.0.0.1:30002 접속 후 개발자도구 네트워크 탭에서 웹 소켓이 생성된 것을 확인한다.
메시지 전송 클릭 시 소켓 메시지에서 데이터가 전달된 것을 확인한다.

node 서버에서 수신한 데이터를 확인한다. 

 

소스코드 참고: https://curryyou.tistory.com/348

 

반응형