[Node.js] μ€μκ° μ±ν μ± λ§λ€μ΄λ³΄κΈ° 1 - Websocket μ΄μ©νμ¬ λ°±μλ ꡬννκΈ° (feat. Websocket) (Build a real-time chatapp 1 - Implement backend with websocket)
μλ νμΈμ 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