โš’ Backend/Node.js

[Node.js] Socket.io๋กœ Room ๊ตฌํ˜„ํ•˜๊ธฐ (feat. TypeScript)

Fomagran ๐Ÿ’ป 2022. 8. 10. 04:58
728x90
๋ฐ˜์‘ํ˜•

์•ˆ๋…•ํ•˜์„ธ์š” Foma ์ž…๋‹ˆ๋‹ค.

 

์˜ค๋Š˜์€ Socket.io๋ฅผ ์ด์šฉํ•˜์—ฌ Room์„ ๊ตฌํ˜„ํ•ด ํŠน์ • Room์— ์žˆ๋Š” ์œ ์ €๋“ค์—๊ฒŒ๋งŒ ๋ฉ”์„ธ์ง€๋ฅผ ๋ณด๋‚ผ ์ˆ˜ ์žˆ๋„๋ก ๊ตฌํ˜„ํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

๋ฐ”๋กœ ์‹œ์ž‘ํ• ๊ฒŒ์š”~


Preview

 


Install

 

typescript, ts-node, express, socket.io ๋ฅผ ์„ค์น˜ํ•ด ์ค๋‹ˆ๋‹ค.

 

npm install typescript
npm install ts-node
npm install express
npm install socket.io
npm install @types/express
npm install @types/socket.io

Model

 

๋ฉ”์„ธ์ง€ ๋ชจ๋ธ์„ ๋งŒ๋“ค์–ด ์ค๋‹ˆ๋‹ค.

 

export interface Message {
  type: string;
  user: string;
  message: string;
  room: string;
}

index.ts

 

express์™€ Message๋ฅผ import ํ•ด์ค๋‹ˆ๋‹ค.

 

import express from "express";
import { Message } from "./models/Message";

 

express ์•ฑ์„ ๋งŒ๋“ค์–ด ์ฃผ๊ณ  http socket.io ์„œ๋ฒ„๋ฅผ ๋งŒ๋“ค์–ด ์ค๋‹ˆ๋‹ค.

 

const app = express();
app.use(express.json());
let http = require("http").Server(app);
let io = require("socket.io")(http);

 

chat ๋„ค์ž„ ์ŠคํŽ˜์ด์Šค๋ฅผ ๋งŒ๋“ค์–ด ์ค๋‹ˆ๋‹ค.

 

const chatRoom = io.of("/chatRoom");

 

* NameSpace๋Š” ์†Œ์ผ“ url์—์„œ ์—”๋“œ ํฌ์ธํŠธ ์—ญํ• ์„ ํ•˜๋ฉฐ ์—ฌ๋Ÿฌ Room๋“ค์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋Š” ๊ณต๊ฐ„์œผ๋กœ ๋ณด์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

 

์œ„์—์„œ ๋งŒ๋“  chat ๋„ค์ž„ ์ŠคํŽ˜์ด์Šค๋กœ connection ๋˜์—ˆ์„ ๋•Œ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด ์ค๋‹ˆ๋‹ค.

 

chat.on("connection", function (socket: any) {	...

 

์„œ๋ฒ„์— ์œ ์ €๊ฐ€ ์ ‘์†ํ•˜์˜€์„ ๋•Œ socket์˜ join() ๋ฉ”์„œ๋“œ์— ๋ฉ”์„ธ์ง€(ํŒŒ๋ผ๋ฏธํ„ฐ) ๊ฐ์ฒด์˜ room์œผ๋กœ ์ ‘์†ํ•˜๋„๋ก ํ•ฉ๋‹ˆ๋‹ค.

 

๊ทธ ๋‹ค์Œ chat ๋„ค์ž„์ŠคํŽ˜์ด์Šค์—์„œ ๋ฉ”์„ธ์ง€์˜ room์— ํ•ด๋‹น ๋ฉ”์„ธ์ง€๋ฅผ ๋ณด๋‚ด๋„๋ก ํ•ฉ๋‹ˆ๋‹ค.

 

  socket.on("welcome", (message: Message) => {
    socket.join(message.room);
    chat.in(message.room).emit("welcome", message);
  });

 

๊ทธ ๋‹ค์Œ ๋ฉ”์„ธ์ง€๊ฐ€ ์™”์„ ๋•Œ๋„ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์ž‘์„ฑํ•ด ์ค๋‹ˆ๋‹ค.

 

  socket.on("message", (message: Message) => {
    chat.in(message.room).emit("message", message);
  });

 

๊ทธ ๋‹ค์Œ ์œ ์ €๊ฐ€ ๋– ๋‚ฌ์„ ๋–„๋Š” socket์˜ leave ๋ฉ”์„œ๋“œ๋ฅผ ํ™œ์šฉํ•˜์—ฌ ํ•ด๋‹น ๋ฉ”์„ธ์ง€์˜ room์—์„œ ๋– ๋‚˜๋„๋ก ํ•ฉ๋‹ˆ๋‹ค.

 

  socket.on("leave", (message: Message) => {
    socket.leave(message.room);
    chat.in(message.room).emit("leave", message);
  });

 

๋งˆ์ง€๋ง‰์œผ๋กœ http ์„œ๋ฒ„๋ฅผ ์‹คํ–‰์‹œ์ผœ ์ค๋‹ˆ๋‹ค.

 

http.listen(3001, function () {
  console.log("listening on:3001");
});

Next Tutorial

 

 

728x90
๋ฐ˜์‘ํ˜•