🧐 🤔 그거 어떻게 쓰더라 🙄 😙

Node.js 웹소켓 간단 예제

2022. 6. 13. Evergood Kim이가 씀

스펙

  • 서버: Node.js
  • 클라이언트: HTML 파일 딸랑 하나

이 예제가 하는 것

서버를 켠 뒤 클라이언트용 html파일을 열면

  1. 클라이언트는
    1. 웹소켓을 연다.
    2. 서버에게 "안녕하세요" 메시지 보낸다.
  2. 서버는
    1. 메시지를 받으면
    2. 받은 메시지를 콘솔에 표시 후
    3. "반갑습니다"를 보낸다.
  3. 클라이언트는 받은 메시지를 콘솔에 표시한다.

예제 코드

서버

터미널에서 다음을 입력하여 ws 모듈 설치

npm install ws

js 코드

const MyWebSocket = require('ws');// 웹소켓 모듈 불러오기
const wss = new MyWebSocket.Server({ port: 8080 });// 서버 만들기

wss.on('connection', function connection( ws ){// 연결이 생기면 ws의 속성들 정의
    ws.on('message', function incoming(message){    //(2)-(1) 메시지를 받으면
        console.log('received: %s', message);       //(2)-(2) 받은 메시지를 콘솔에 표시해보기
        ws.send('반갑습니다.');                      //(2)-(3) "반갑습니다"를 보낸다.
    })
    // ... ws의 그 외 속성
})
ws의 그 외 속성
    //// 오류 처리
    ws.on('error', (err)=>{
        console.error(err);// 콘솔에 표시해보기
    })
    //// 종료
    ws.on('close', ()=>{
        console.log('클라이언트 접속 해제');
    })
클라이언트

내용물 아무것도 없고 딱 소켓 메시지 주고받는 스크립트 하나만 덜렁 있다.

<!DOCTYPE html>
<html><head><title>websocket ex</title></head><body><script>


const webSocket = new WebSocket("ws://localhost:8080");//(1)-(1) 웹소켓 열기 // 현재는 주소가 로컬호스트로 되어있다.

webSocket.onopen = function(){           // 소켓이 열렸으면
  console.log("Web Socket Connected");   // 열렸다고 콘솔에 찍기
  webSocket.send('안녕하세요');           //(1)-(2) 서버에 메시지 보내보기
}

webSocket.onmessage = function( message ){//(3) 메시지 받았으면
  console.log( message.data );            //(3) 콘솔에 표시
}


</script></body></html>

다른 서버와 포트 공유

HTTP 서버와 같은 포트 공유

소켓 만들 때 포트번호 대신 서버 넣기

//// HTTP 서버
const http = require('http');// http 모듈
const server = http.createServer((req, res)=>{}).listen(8080);// http 서버 열기

//// 같은 포트로 소켓
const MyWebSocket = require('ws');// 소켓 모듈
const wss = new MyWebSocket.Server({server});// 만들어진 http 서버에 소켓 열기 // 중괄호 필요

express 서버와 같은 포트 공유

const express = require('express');// express 모듈
const app = express();
const WebSocket = require('ws');

app.set('port', 8080);
const server = app.listen( … );// app.listen을 서버로 받는다

const wsss = new WebSocket.Server({server});// 만들어진 express 서버에 소켓 열기
728x90

카테고리 다른 글