socket.io 예제 따라하기

socket.io 예제 따라하기


socket 통신을 nodejs로 구현한 내용이다.


한번 정리해보기로 한다.


1. 채팅 소스 

공식 사이트에 있는 예제 소스이다.

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

간단한 채팅 소스이다.

git을 통해 예제를 받아 볼수 있다.

git clone https://github.com/socketio/chat-example.git




딱 채팅만 동작하는 소스이다.


실행 방법은

1. git으로 당기고

 git clone https://github.com/socketio/chat-example.git

2. 해당 폴더로 이동하고 

 cd chat-example/

3. 초기화 하고 

yarn

4. 실행한다.

yarn start

5. 브라우저 2개를 열어서 위의 이미지와 같이 메시지를 입력하면 끝이다.





소스를 확인해 보겠다.



보아야 할 소스는 2개 밖에 없다.

index.js 와 index.html 2개이다.

먼저 index.js 를 보면



const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;

console.log(process.env.PORT)

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  socket.on('chat message', msg => {
    io.emit('chat message', msg);
  });
});

http.listen(port, () => {
  console.log(`Socket.IO server running at http://localhost:${port}/`);
});




간단하다.

1. 선언하고 

const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;

2. route 설정하고

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

3. io 의 on 하나 달고

io.on('connection', (socket) => {
  socket.on('chat message', msg => {
    io.emit('chat message', msg);
  });
});

4. listen을 한다.

http.listen(port, () => {
  console.log(`Socket.IO server running at http://localhost:${port}/`);
});


실행하면 아래와 같이 console 로 나온다. 

pi@raspberrypi:~/chat-example $ yarn start
yarn run v1.22.10
$ node index.js
undefined
Socket.IO server running at http://localhost:3000/

console 에서는 아무런 메시지가 없다. 

그냥 서버만 켰다는 것이다.


여기서 중요한 부분은 3번에 io 의 on 부분이다.

이부분이 왜 중요한지는 아래의 index.html 파일을 확인하면서 설명하도록 하겠다.


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="formaction="">
      <input id="inputautocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>

    <script>
      var socket = io();

      var messages = document.getElementById('messages');
      var form = document.getElementById('form');
      var input = document.getElementById('input');

      form.addEventListener('submit', function(e) {
        e.preventDefault();
        if (input.value{
          socket.emit('chat message', input.value);
          input.value = '';
        }
      });

      socket.on('chat message', function(msg) {
        var item = document.createElement('li');
        item.textContent = msg;
        messages.appendChild(item);
        window.scrollTo(0, document.body.scrollHeight);
      });
    </script>
  </body>
</html>


내용은 

<header> 는 css style sheet  가 적용되어 있고

<body> 는 ul tag와 form 2개로 구성되어 있다.

메시지를 받으면 ul에 li 를 추가하는 형태로 구현되어 있다.

input text 를 받아서 button 을 submit 처리해서 서버로 값을 넘기는 구조이다.



마지막으로 <script> 부분이 중요한 부분이다.


    <script src="/socket.io/socket.io.js"></script>


chrome borowser 의 debug 를 창에 Source ㄹ르 확인하면 아래와 같이 나온다.


이건 node 를 실행하면 node_module에 socket.io 아래에 있는 내용이다.


 <script src="/socket.io/socket.io.js"></script>

    <script>
      var socket = io();

      var messages = document.getElementById('messages');
      var form = document.getElementById('form');
      var input = document.getElementById('input');

      form.addEventListener('submit', function(e) {
        e.preventDefault();
        if (input.value{
          socket.emit('chat message', input.value);
          input.value = '';
        }
      });

      socket.on('chat message', function(msg) {
        var item = document.createElement('li');
        item.textContent = msg;
        messages.appendChild(item);
        window.scrollTo(0, document.body.scrollHeight);
      });
    </script>

소스의 내용은 

1. socket을 사용하기 위해서 선언하고

  var socket = io();

2. dom 객체를 정의하고

 var messages = document.getElementById('messages');
      var form = document.getElementById('form');
      var input = document.getElementById('input');

3. submit 이 발생하면 socket으로 데이터를 전송하고

form.addEventListener('submit', function(e) {
        e.preventDefault();
        if (input.value{
          socket.emit('chat message', input.value);
          input.value = '';
        }
      });

    socket.emit('chat message',input.value) 는 index.js 에 3번에 io 의 on을 호출한다.

emit 에 'chat message' 라는 부분을 호출한다.


4. 서버에서 받은 message를 출력하는 구조이다.

 socket.on('chat message', function(msg) {
        var item = document.createElement('li');
        item.textContent = msg;
        messages.appendChild(item);
        window.scrollTo(0, document.body.scrollHeight);
      });


index.js 에 3의 내용

io.on('connection', (socket) => {
  socket.on('chat message', msg => {
    io.emit('chat message', msg);
  });
});

의 socket.on('chat message' 부분이 client 에서 호출된 것을 다시 io.emit('chat message' 형태로 다시 client 로 뿌려주는데 그부분을 받는 부분이다. 



아래 그림을 참조하기 바란다.



이 내용은 

https://socket.io/get-started/chat#Getting-this-example 의 내용을 설명한 것이고

추가로 Homework 가 있는데 그건 따로 하나식 해 보도록 하겠다.







댓글

이 블로그의 인기 게시물

mount 명령 ( 읽기 권한만 있는놈 쓰기 권한 주기 )

c# mqtt client example

비글본 블랙 고정 아이피 설정