본문 바로가기
Web/Backend

[NodeJS] 소켓을 이용한 간단한 채팅방 만들기

by r4bb1t 2020. 4. 30.
반응형

net 모듈을 이용하여 TCP 프로토콜로 서버-클라이언트 간 데이터를 전송하는 코드이다.

 

서버 |

socket-server.js

const net = require("net");

let pool = [];

const server = net.createServer((socket) => {
  pool.push(socket);
  socket.on("data", (data) => {
    let d = JSON.parse(data);
    switch (d.type) {
      case "CONNECT":
        for (let s of pool) s.write(d.content + " connected!");
        break;
      case "CHAT":
        for (let s of pool) s.write(d.content);
        break;
    }
  });
  socket.on("error", (e) => {
    const exitSocket = pool.findIndex((item) => item === socket);
    if (exitSocket > -1) pool.splice(exitSocket, 1);
    for (let s of pool) s.write("Someone's out.");
  });
});

server.listen(5000, () => {
  console.log("listening 5000");
});

 

1. 연결 관리하기

하나의 서버에 클라이언트 여러 개가 연결되므로, 이를 pool 배열을 이용하여 관리해 준다.

연결이 들어올 때마다 pool.push(socket)으로 연결을 pool 배열에 넣어주고, 아래 2. 클라이언트에 채팅 보내기와 같은 프로세스로 모든 클라이언트에 새 연결이 들어왔음을 알려준다.

또 연결이 끊길 때는 에러를 캐치해서, pool 배열 내에서 현재 연결을 찾아준 후 pool.splice()로 배열에서 뺀다. (에러를 캐치하지 않으면 클라이언트 하나가 끊기면 서버도 에러를 내면서 같이 끊긴다.)

 

2. 클라이언트에 채팅 보내기

모든 연결에 전부 채팅을 보내야 하므로, for (let s of pool)로 pool의 모든 원소들에 write를 해준다.


클라이언트 |

socket-client.js

const net = require("net");
const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const client = net.connect({ port: 5000, host: "localhost" });

client.on("connect", () => {
  rl.question("Name : ", (name) => {
    client.write(
      JSON.stringify({
        type: "CONNECT",
        content: `${name}`,
      })
    );
    rl.on("line", function (line) {
      client.write(
        JSON.stringify({
          type: "CHAT",
          content: `${name} : ${line}`,
        })
      );
    });
  });
});

client.on("data", (data) => {
  console.log(data.toString());
});

client.on("close", () => {
  console.log("ended");
});

 

1. 이름 입력

이름 입력 후 메세지를 입력하는 게 자연스러우므로, question의 콜백에 line을 입력받게 했다.

 

2. 서버에 채팅 보내기

클라이언트에서 보내는 데이터는 두 종류이고, 형식은 JSON이다.

서버에서 데이터를 받은 후 어떤 데이터인지 알 수 있도록 type 변수를 넣었다.

CONNECT / 연결이 되었음을 알리고, 입력받은 이름을 서버에 전달한다.

CHAT / 입력받은 line을 name과 함께 서버에 전달한다.


실행 화면은 이렇다. 각각 서버 / 클라이언트1 / 클라이언트2.

이름을 입력받고 채팅을 주고받은 후 클라이언트2가 접속을 종료한 상황이다.

반응형

댓글