본문 바로가기

Programming/NodeJS

[NodeJS] NodeJS + Express + Socket.IO 로 간단한 채팅 구현하기

작성자 : Deok

이번에는 간단히 NodeJS + Express + Socket.IO 를 이용해 간단한 채팅프로그램을 만들어 보겠습니다. 


* 저장기능은 없습니다.

* 포스팅 전 코드를 공유 드리겠습니다.


소스 코드 : https://github.com/DeokME/example-socketio-chat



우선 NodeJS 를 이용함으로 NodeJS 와 Express + Express generate 를 설치해야 합니다. 환경 설정이 안되신 분들은 아래의 포스트들을 참고하시기 바랍니다.


2019/06/04 - [강좌/NodeJS] - [NodeJS] Linux ( CentOS, Ubuntu, AWS Linux 등 ) 에 NodeJS 설치하기

2019/06/04 - [강좌/NodeJS] - [NodeJS] yarn 을 설치하고 yarn 을 이용하여 패키지 관리하기

2019/06/04 - [강좌/NodeJS] - [NodeJS] n 을 통하여 NodeJS 버전 변경하기

2019/06/04 - [강좌/NodeJS] - [NodeJS] pm2 를 통하여 NodeJS 프로세스 관리하기

2019/06/05 - [강좌/NodeJS] - [NodeJS] NodeJS + Express 설치 및 서비스 개발 시작하기



1. Express Generator 를 이용하여 프로젝트 셋팅하기


환경 설정이 모두 완료 되었다면 이제 아래의 명령어로 프로젝트를 생성합니다.

# express generator 를 이용하여 프로젝트 생성
$ express socketio-chat

# 생성된 프로젝트로 이동
$ cd socketio-chat

# socketio 


생성이 정상적으로 되었다면 node start 를 통해 서버가 정상적으로 작동 되는지 확인 하도록 합니다.




2. 기본 패키지 및 Socket.IO 설치 및 추가


이제 프로젝트 생성이 완료 되었으니 필요한 패키지를 설치 합니다.

$ npm install
$ npm install socket.io -save
$ npm install serve-favicon --save

# 혹은

$ yarn install
$ yarn add socket.io
$ yarn add serve-favicon


이제 모든 환경 설정이 끝났고 코드 작성으로 들어가겠습니다.



3. 프로그램 코드 작성


우선 채팅을 위한 페이지를 보여주기 위해 채팅 관련 라우터 ( Route ) - ./routes/chat.js 를 추가하고 아래의 코드를 입력해 주도록합니다.

- ./routes/chat.js

var express = require('express');
var router = express.Router();

/* GET chat listing. */
router.get('/', function(req, res, next) {
    res.render('chat', { title: 'chat tutorial' }); // View 에 chat.jade 를 추가해야됨

});
 
module.exports = router;


이제 app.js 에 위에서 생성한 chat 라우트를 추가해 주고

- app.js

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
# 위의 코드 하단에 추가
var chatRouter = require('./routes/chat'); // 추가됨


같은 app.js 파일에 채팅을 위해 하단 module.exports = router; 위쪽에 app.io 로 socket.io 코드를 입력합니다.

- app.js

/*** Socket.IO 추가 ***/
app.io = require('socket.io')();

app.io.on('connection', function(socket){
   
  console.log("a user connected");
  socket.broadcast.emit('hi');
   
  socket.on('disconnect', function(){
      console.log('user disconnected');
  });
   
  socket.on('chatMessage', function(msg){
      console.log('message: ' + msg);
      app.io.emit('chatMessage', msg);
  }); 

});

module.exports = router;


또 express generator 와 함께 실행하기 위해 ./bin/www.js 파일의 var server = http.createServer(app); 아래에 코드를 추가해 주도록 합니다.

var server = http.createServer(app);
app.io.attach(server); // 추가됨




마지막으로 views 로 이동하여 view 를 위한 chat.jade 를 추가하고 아래의 코드를 넣어 주도록 합니다. * express 는 기본적으로 jade 템플릿을 이용하기 때문에 jade 를 이용했습니다.

extends layout
 
block content
    ul#messages
    form(action='')
      input#m(autocomplete='off')
      button Send
     
    style.
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { padding:0px; font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
 
       
    script(src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.slim.js')
    script(src='http://code.jquery.com/jquery-1.11.1.js')
    script.
       
      var socket = io();
       
      $('form').submit(function(){
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
        return false;
      });
       
      socket.on('chat message', function(msg){
        $('#messages').append($('<li>').text(msg));
      });


이제 코드 작성이 완료 되었습니다.


4. 채팅서버 실행 & 테스트하기


이제 서버를 아래의 명령어로 실행하고 테스트해보도록 합니다.

$ npm start


서버가 정상적으로 실행 되었다면 http://localhost:3000/chat 혹은 http://주소:3000/chat 로 이동하신 후 테스트를 진행하실 수 있습니다.



즐거운 개발 되시기 바랍니다 :D