on
[VanillaJS, Node.js] Zoom Clone Coding-1.1. WebSocket install
[VanillaJS, Node.js] Zoom Clone Coding-1.1. WebSocket install
728x90
1. terminal 창에서 websocket을 install 한다.
> npm i ws
-ws 서버를 만들지 않고 만들어진 express 서버에 합친다.
-ws와 express 는 다른 프로토콜임 → express는 http를 다룬다.
< server.js >
import http from "http"; import WebSocket from "ws"; import express from "express"; const app = express(); app.set('view engine', "pug"); app.set("views", __dirname+"/views"); app.use("/public", express.static(__dirname+"/public")); app.get("/", (req, res) => res.render("home")); app.get("/*", (req, res) => res.redirect("/")); const handleListen = () => console.log(`Listening on http://localhost:3000`); const server = http.createServer(app); const wss = new WebSocket.Server({server});
2. http를 import 한다.
- http는 이미 nodejs에 설치되어 있으므로 따로 install 할 필요 없음
const server = http.createServer(app);
- express application인 app으로부터 서버 생성
- 변수 server를 통해 서버에 접근 가능
3. ws를 import 한다.
const wss = new WebSocket.Server({server});
- WebSocket.Server 에 http서버인 server를 전달해주므로써 http서버, ws서버를 모두 돌릴 수 있게 되었다.
둘 중 하나만 있어도 되는데 현재 둘 다 사용하려는 이유는 http와 ws 서버가 같은 port에 있길 원하기 때문이다.
→ 즉, 동일한 port에서 http, ws request 를 모두 처리할 수 있기 때문이다.
→ https://localhost:3000 와 ws://localhost:3000 모두 작동
728x90
from http://mingmeng030.tistory.com/173 by ccl(A) rewrite - 2021-09-13 16:01:01