P_eli 2023. 12. 19. 19:18
728x90
반응형

이 예제에서는 Express와 Socket.io를 사용하여 실시간으로 메시지를 전송하는 간단한 채팅 애플리케이션을 만들어볼 것입니다.

 

프로젝트 초기화

먼저, 프로젝트 폴더를 생성하고 해당 폴더로 이동합니다.

mkdir nodejs-chat-app
cd nodejs-chat-app

 

의존성 설치

다음으로, 프로젝트에 필요한 의존성을 설치합니다.

npm init -y
npm install express socket.io

 

서버 코드 작성

index.js 파일을 생성하고 다음과 같이 코드를 작성합니다.

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIO(server);

// 정적 파일 제공 (옵션)
app.use(express.static(__dirname + '/public'));

// 루트 경로로 접속했을 때
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

// 소켓 연결 시
io.on('connection', (socket) => {
  console.log('사용자가 접속했습니다.');

  // 채팅 메시지 수신 시
  socket.on('chat message', (msg) => {
    console.log('메시지: ' + msg);

    // 모든 클라이언트에게 메시지 전송
    io.emit('chat message', msg);
  });

  // 연결 종료 시
  socket.on('disconnect', () => {
    console.log('사용자가 나갔습니다.');
  });
});

// 서버 3000번 포트로 실행
server.listen(3000, () => {
  console.log('서버가 3000번 포트에서 실행 중입니다.');
});

 

클라이언트 코드 작성

프로젝트 폴더에 public 폴더를 생성하고, 그 안에 index.html 파일을 만듭니다.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>웹 채팅 앱</title>
  <style>
    body {
      font-family: 'Arial', sans-serif;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-color: #f4f4f4;
    }

    #chat-box {
      width: 300px;
      border: 1px solid #ddd;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    #messages {
      list-style-type: none;
      margin: 0;
      padding: 10px;
      overflow-y: scroll;
      height: 300px;
    }

    #messages li {
      margin-bottom: 8px;
    }

    #form {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      background-color: #fff;
    }

    #m {
      flex: 1;
      padding: 8px;
      margin-right: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
    }

    #send-button {
      padding: 8px 16px;
      background-color: #4caf50;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <!-- 사용자 이름을 입력받는 창 -->
  <div id="username-input">
    <label for="username">사용자 이름:</label>
    <input type="text" id="username" />
    <button id="set-username">설정</button>
  </div>

  <div id="chat-box" style="display:none;">
    <!-- 메시지를 표시할 영역 -->
    <ul id="messages"></ul>
  </div>

  <!-- 채팅 입력 폼 -->
  <form id="form" action="" style="display:none;">
    <input id="m" autocomplete="off" placeholder="메시지를 입력하세요" />
    <button id="send-button">전송</button>
  </form>

  <!-- Socket.IO 및 jQuery 스크립트 로드 -->
  <script src="/socket.io/socket.io.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>

  <!-- 채팅 클라이언트 스크립트 -->
  <script>
    $(function () {
      var socket = io();
      var username = '';

      // 사용자 이름을 설정하는 함수
      $('#set-username').click(function () {
        var enteredUsername = $('#username').val().trim();
        if (enteredUsername !== '') {
          username = enteredUsername;
          $('#username-input').hide();
          $('#chat-box').show();
          $('#form').show();
        }
      });

      // 채팅 메시지를 전송하는 함수
      $('#form').submit(function () {
        var message = $('#m').val().trim();
        if (message !== '') {
          socket.emit('chat message', { username: username, message: message });
          $('#m').val('');
        }
        return false;
      });

      // 채팅 메시지를 받아서 화면에 추가하는 함수
      socket.on('chat message', function (data) {
        var msg = data.username + ': ' + data.message;
        $('#messages').append($('<li>').text(msg));
        // 스크롤을 항상 가장 아래로 유지
        $('#chat-box').scrollTop($('#chat-box')[0].scrollHeight);
      });
    });
  </script>
</body>
</html>

 

실행

마지막으로, 터미널에서 다음 명령어로 서버를 실행합니다.

node index.js

 

웹 브라우저에서 http://localhost:3000에 접속하여 채팅을 테스트해볼 수 있습니다.

 

 

728x90
반응형