Lined Notebook

[Android] Node.js Socket.io 통신 - 1

by JungWook_

mcu에서 server로 데이터를 전송하고 server에서 mcu로 명령어를 전송해야 하는 일이 생겼습니다.

 

기존에는 mcu에서 bluetooth로 android에 데이터를 전송해 serial monitor로 사용하고 android에서 post방식으로 server에 데이터를 전송해 터미널 로그를 이용해서 확인했는데 양방향 통신이 어려워서 socket.io를 사용하기로 했습니다.

 

이번 글에서는 android와 node.js사이에서 socket.io를 이용해 통신하는 방법을 적어두려고 합니다. 구글링을 통해 몇 가지 예제를 실행해 봤는데 실행이 잘 안됐습니다. server가 안 되는 건지 android가 안 되는 건지 파악이 어려워서 web과 node.js서버 간의 통신부터 구현한 다음에 web을 android로 옮기겠습니다.

먼저 server를 구현하겠습니다.

 

저는 aws에서 ubuntu 16.04버전을 사용 중입니다.


Node.js 설치

Node.js

위 사이트에서 받을 수도 있지만 편리한 패키지 매니저를 사용하겠습니다.

sudo apt-get update
sudo apt-get install nodejs

node.js를 설치했다면 npm도 설치해줍니다.

 

sudo apt-get install npm

설치가 다 됐다면 다음 명령어를 통해서 확인해봅시다.

 

nodejs -v

저는 v12.0.0이라고 나옵니다. 설치가 잘 됐습니다.

 


Socket.io 설치

Socket.io

이번에도 패키지 센터를 이용해서 설치하겠습니다.

 

npm install --save express@4.15.2

express를 이용하면 편하니까 설치하겠습니다.

 

npm install --save socket.io

그 다음 socket.io를 설치합니다.

 

app.js

더보기
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

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

io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
      console.log('user disconnected');
    });

    socket.on('msg', function(msg){
        console.log('message: ' + msg);
        io.emit('msg', msg);
    });
});

http.listen(8080, function(){
  console.log('listening on *:8080');
});

 

index.html

더보기
<!doctype html>
<html>
  <head>
    <title>Tango Socket</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { 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 0 50px 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
            $(function () {
              var socket = io();
              $('form').submit(function(e){
                e.preventDefault(); // prevents page reloading
                socket.emit('msg', $('#m').val());
                $('#m').val('');
                return false;
              });
              socket.on('msg', function(msg){
                $('#messages').append($('<li>').append($('<pre>').text(msg)));
                $('html, body').scrollTop($(document).height());
              });
            });
          </script>
  </body>
</html>

먼저 app.js를 보겠습니다.

다른건 볼거없고 socket을 받을때는 .on 보낼때는 .emit을 사용하면 됩니다. 첫 번째 인자는 이벤트의 이름이고 두번째 인자에는 데이터가 들어갑니다.

 

index.html에서는 socket을 받으면 li태그에 데이터를 붙여서 뿌려줍니다. 나머지 내용은 다음 글에서 쓰겠습니다.

블로그의 정보

hongmono

JungWook_

활동하기