์๋ ํ์ธ์ Foma ์ ๋๋ค.
์ค๋์ Node.js์์ Websocket์ ์ด์ฉํ์ฌ ์ค์๊ฐ ์๋ฒ๋ฅผ ๊ตฌํํด ๋ณด๋ ค๊ณ ํฉ๋๋ค.
๋ฐ๋ก ์์ํ ๊ฒ์~
(๋ฐฑ์๋ ์๋ฒ๋ฅผ ์ด๊ธฐํ ํ๋ ๋ฐฉ๋ฒ์ ์๋ตํ๊ณ ์งํํฉ๋๋ค. ํน์ ๋ชจ๋ฅด์๋ ๋ถ๋ค์ ์ฌ๊ธฐ ์์ ํ์ธํด ์ฃผ์ธ์!)
Tutorial
- ์ค์๊ฐ ์ฑํ ์ฑ ๋ง๋ค์ด๋ณด๊ธฐ 1 - Websocket ์ด์ฉํ์ฌ ๋ฐฑ์๋ ๊ตฌํํ๊ธฐ (feat. Websocket) (Build a real-time chatapp 1 - Implement backend with websocket)
- ์ค์๊ฐ ์ฑํ ์ฑ ๋ง๋ค์ด๋ณด๊ธฐ 2 - Websocket ์ด์ฉํ์ฌ ํ๋ก ํธ ๊ตฌํํ๊ธฐ (Build a real-time chatapp 1 - Implement frontend with websocket)
Install
express
๊ฐ๋จํ๊ฒ ์๋ฒ๋ฅผ ๋ง๋ค ์ ์๋๋ก ๋์์ฃผ๋ ๋ชจ๋
npm install express@4.18.1
cors
HTTP์ ๋์ผ ์ถ์ฒ ์ ์ฑ ์ ํด๊ฒฐํ๊ธฐ ์ํ ๋ชจ๋
npm install cors@2.8.5
nodemon
์์ค ์ฝ๋ ๋ณ๊ฒฝ ์ ์๋์ผ๋ก ์๋ฒ๊ฐ ์ฌ์คํ ๋๋๋ก ๋์์ฃผ๋ ๋ชจ๋
npm install nodemon@2.0.14
socket.io
์ค์๊ฐ ์๋ฒ๋ฅผ ๋ง๋ค ์ ์๋๋ก ๋์์ฃผ๋ ๋ชจ๋
npm install socket.io@4.5.1
Implemet a websocket
์๋๋ ์ค์๊ฐ ์น์์ผ์ ๋ง๋ค๊ธฐ ์ํด ํ์ํ ๋ณ์๋ค์ ๋๋ค.
const express = require("express");
const app = express();
const http = require("http");
const WebSocket = require("ws");
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const port = 3001;
์ฐ์ ์น ์์ผ ์๋ฒ๋ฅผ ์ฐ๊ฒฐํด ์ค๋๋ค.
wss.on("connection", (ws) => {
...
๊ทธ ๋ค์ message๋ฅผ ์์ ํ ์ ์๋๋ก ์ธํ ํด ์ค๋๋ค.
ws.on("message", (message) => {
...
์น ์๋ฒ ์์ผ์ ํด๋ผ์ด์ธํธ๋ค๋ก๋ถํฐ ๋ฐ์ ๋ฐ์ดํฐ๋ฅผ forEach ํจ์๋ก ๋ชจ๋ ์ํํฉ๋๋ค.
wss.clients.forEach(function each(client) {
...
๋ง์ฝ ํด๋ผ์ด์ธํธ์ ์ค๋น ์ํ๊ฐ ์น์์ผ์ด OPEN์ธ ์ํ๋ผ๋ฉด ์์ ํ ๋ฉ์ธ์ง๋ฅผ JSON์ผ๋ก ํ์ฑํ ๋ค ํ์ฑํ ๋ฐ์ดํฐ๋ฅผ ๋ค์ stringํ ์์ผ์ ํด๋ผ์ด์ธํธ์ ์ ์กํฉ๋๋ค.
if (client.readyState === WebSocket.OPEN) {
let parse = JSON.parse(message);
let stringify = JSON.stringify(parse);
client.send(stringify);
}
์๋ฒ๊ฐ ์ ์๋๋๋์ง ํ ์คํธ ํด๋ณด๊ฒ ์ต๋๋ค.
app.get("/", (req, res) => {
res.send("Hello World!");
});
server.listen(port, () => console.log(`Server running on ${port}`));
์๋์ ๊ฐ์ด ์ ์๋๋๋๊ตฐ์.
index.js
const express = require("express");
const app = express();
const http = require("http");
const WebSocket = require("ws");
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const port = 3001;
wss.on("connection", (ws) => {
ws.on("message", (message) => {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
let parse = JSON.parse(message);
let stringify = JSON.stringify(parse);
client.send(stringify);
}
});
});
});
app.get("/", (req, res) => {
res.send("Hello World!");
});
server.listen(port, () => console.log(`Server running on ${port}`));
Source Code
GitHub - fomagran/ChattingAppFullStack
Contribute to fomagran/ChattingAppFullStack development by creating an account on GitHub.
github.com
๋๊ธ