ABOUT ME

개발에 대한 내용을 주로 기록하고, 그 외에 남기고 싶은 것들을 기록합니다.

Today
Yesterday
Total
  • [NodeJs] 채팅 서버 만들어서 실행하기
    프레임워크/NodeJs 2022. 5. 29. 00:56

    채팅 서버를 간단하게 오픈할 수 있도록 만들어보겠습니다.

    Socket.io를 사용하였고, 공식 홈페이지에 나와있는 대로 구현해보려고 합니다.

    https://socket.io/get-started/chat

     

     

    NodeJS 설치 후 npm 프로젝트 생성을 합니다

    $ npm init

     

     

    맨 처음 npm init 명령어를 실행하면 package.json 파일이 생성됩니다

    {
      "name": "chat-socket",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC"
    }

     

     

    ES6 문법을 사용하기 위해 babel을 npm module로 설치합니다

    $ npm install @babel/core @babel/node @babel/preset-env --save-dev

     

    설치 후 프로젝트의 root 경로에 .babelrc 파일을 만들어 아래와 같이 설정해줍니다

    {
        "presets": ["@babel/preset-env"]
    }

     

    그리고 package.json 파일을 열어 babel-node를 앞에 붙여줍니다

    {
    	// ...
    	"scripts": {
            "develop": "babel-node app.js"
    	}
        
        // ...
    }

     

     

     

    이제 본격적으로 Socket.io를 이용한 채팅을 만들어 보겠습니다

    우선 저는 채팅 서버를 express로 돌리기위해 socket.io와 express를 npm module로 설치했습니다

    $ npm install socket.io
    $ npm install express --save

     

    서버 (app.js)

    import express from 'express';
    import http from 'http';
    import { Server } from 'socket.io';
    
    const app = express();
    const server = http.createServer(app);
    
    const io = new Server(server);
    
    app.get('/', (req, res) => {
        res.sendFile(__dirname + '/index.html');
    });
    
    io.on('connection', (socket) => {
        console.log('user connected');
    
    	// 'chat message'로 오는 메세지를 받음
        socket.on('chat message', (msg) => {
        	// 받은 메세지를 'chat message'로 보냄
            io.emit('chat message', msg);
        });
    });
    
    server.listen(3000, () => {
        console.log('listening on *:3000');
        console.log('http://localhost:3000/');
    });

     

    클라이언트 (index.html)

    <!DOCTYPE html>
    <html>
        <head>
            <title>Socket.IO chat</title>
            <style>
                body {
                    margin: 0;
                    padding-bottom: 3rem;
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
                }
    
                #form {
                    background: rgba(0, 0, 0, 0.15);
                    padding: 0.25rem;
                    position: fixed;
                    bottom: 0;
                    left: 0;
                    right: 0;
                    display: flex;
                    height: 3rem;
                    box-sizing: border-box;
                    backdrop-filter: blur(10px);
                }
                #input {
                    border: none;
                    padding: 0 1rem;
                    flex-grow: 1;
                    border-radius: 2rem;
                    margin: 0.25rem;
                }
                #input:focus {
                    outline: none;
                }
                #form > button {
                    background: #333;
                    border: none;
                    padding: 0 1rem;
                    margin: 0.25rem;
                    border-radius: 3px;
                    outline: none;
                    color: #fff;
                }
    
                #messages {
                    list-style-type: none;
                    margin: 0;
                    padding: 0;
                }
                #messages > li {
                    padding: 0.5rem 1rem;
                }
                #messages > li:nth-child(odd) {
                    background: #efefef;
                }
            </style>
        </head>
        <body>
            <ul id="messages"></ul>
            <form id="form" action=""><input id="input" autocomplete="off" /><button>Send</button></form>
    
            <script src="/socket.io/socket.io.js"></script>
            <script>
                const socket = io();
    
                // script를 body안에 두어야 element들이 null이 안뜬다
                const messages = document.getElementById('messages');
                const form = document.getElementById('form');
                const input = document.getElementById('input');
    
                form.addEventListener('submit', function (e) {
                    e.preventDefault();
                    if (input.value) {
                        // 작성된 채팅 내용을 'chat message'로 보냄
                        socket.emit('chat message', input.value);
                        input.value = ''; // 입력칸 초기화
                    }
                });
    
                // 받은 채팅 내용을 화면에 뿌려줌
                socket.on('chat message', function (msg) {
                    const item = document.createElement('li');
                    item.textContent = msg;
                    messages.appendChild(item);
                    window.scrollTo(0, document.body.scrollHeight);
                });
            </script>
        </body>
    </html>

     

     

    위와 같이 파일을 작성한 후 실행합니다

    $ npm run develop

     

    http://localhost:3000/ 로 접속하여 실행하면 아래와 같이 정상 실행됩니다

     

     

    댓글

Designed by Tistory.