NomadCoders/Zoom-Clone

[#06] WebSoket Events

Heoky 2022. 7. 12. 04:37

WS를 사용해서 back-end와 front-end 사이에서 첫번째 connection(연결)을 만들어보자.

참고: MDN


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 });

function handleConnection(soket) {
  console.log(soket);
}

wss.on('connection', handleConnection);

server.listen(3000, handleListen);

참고: ws-npm


app.js

const URL = `ws://${window.location.host}`;
const aWebSocket = new WebSocket(URL);

참고: MDN


새로고침 시 서버의 console을 확인 해보자.

서버에서 console을 통해 soket을 확인 할 수 있다. 이것들이 WebSoket이다.

WebSoket은 브라우저와 서버 사이의 연결이다.


server.js

// 인자로 받아온 soket은 연결된 브라우저를 뜻함
function handleConnection(soket) {
  console.log(soket); // 여기서 access를 할 수 있다.
}

wss.on('connection', handleConnection);

access(입장, 접근)는 위의 함수 안에서 할 수 있다. 받아온 인자 soket이 front-end와 실시간(real-time)으로 소통할 수 있다.


마찬가지로 front-end도 soket을 가지고 있다. ( 참고: MDN )

const URL = `ws://${window.location.host}`;
const aWebSocket = new WebSocket(URL); // 서버로의 연결을 뜻함

 

'NomadCoders > Zoom-Clone' 카테고리의 다른 글

[#07] WebSoket Messages  (0) 2022.07.12
[#05] WebSokets in NodeJS  (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