WebSoket framework를 다루기 전 WS에 대해 알아볼 것이다.
WebSoket core 즉, WebSoket 기반이고 기초이기 때문이다.
ws: a Node.js WebSocket library 말 그대로 WebSocket 라이브러리이다. 여기에서 WS의 사용법에 대해 기록하려 한다.
https://www.npmjs.com/package/ws#installing
ws
Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js. Latest version: 8.8.0, last published: a month ago. Start using ws in your project by running `npm i ws`. There are 13030 other projects in the npm registry using ws
www.npmjs.com
현재 프로젝트의 기본적인 서버 구성에서는 HTTP를 다루고 있다. 응답과 요청만이 가능하다.
HTTP와 WebSocket은 프로토콜이 서로 다르지만 하나의 서버(같은 port)에서 구동될 수 있도록 합치도록 할 것이다.
express에서는 WS를 지원하지 않기 때문에 Function을 추가 할 것인데, 아래의 코드를 보며 설명을 기록하고자 한다.
(Socket.IO 공식문서를 참고해도 됨)
server.js
const http = require('http');
const WebSoket = require('ws');
const express = require('express');
const app = express();
// pug로 view engine을 설정, express에 template이 어디 있는지 지정
app.set('view engine', 'pug');
app.set('views', __dirname + '/views');
// public url을 생성해서 유저에게 파일을 공유
app.use('/public', express.static(__dirname + '/public'));
// home.pug를 render 해주는 router handler를 만든다.
app.get('/', (_, res) => res.render('home')); // router handler, 현재 프로젝트에서는 home url만 쓸 것이다.
app.get('/*', (_, res) => res.redirect('/')); // user가 어떤 url로 이동하던지 home으로 돌려보낸다.
const handleListen = () => console.log(`Listening in http://localhost:3000/`);
// 같은 서버에서 http, webSoket 둘 다 작동 시킬 수 있다.
const server = http.createServer(app);
const wss = new WebSoket.Server({ server });
server.listen(3000, handleListen);
WS 사용법 참고: Usage examples
'NomadCoders > Zoom-Clone' 카테고리의 다른 글
[#07] WebSoket Messages (0) | 2022.07.12 |
---|---|
[#06] WebSoket Events (0) | 2022.07.12 |
[#04] HTTP vs WebSokets (0) | 2022.07.12 |
[#03] Recap (0) | 2022.07.11 |
[#02] Frontend Setup (0) | 2022.07.07 |