LoginSignup
13
17

More than 5 years have passed since last update.

[Node.js <-> Node.js] Socket.ioでサーバー間通信メモ

Posted at

Node.jsとNode.jsで双方向通信をさせてみます。

その辺の連携するときいつもはMilkcocoaFirebaseを使いますが、なぜか今日はMilkcocoaもFirebaseも調子悪いみたいで...

この記事が参考になりました。

Node.js+Socket.ioを利用してサーバ<->サーバ間通信

サーバー側

socket.io公式チュートリアルのチャットを作ります。

npm i --save socket.io express
index.html
<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</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; 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(){
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      return false;
    });
    socket.on('chat message', function(msg){
      $('#messages').append($('<li>').text(msg));
    });
  });
</script>

</body>
</html>
server.js
'use strict';

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

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

io.on('connection', (socket) => {
    console.log('a user connected');
    socket.on('chat message', (msg) => {
        io.emit('chat message', msg);
        console.log(`message: ${msg}`);
    });
});

http.listen(PORT, () => console.log(`listening on *:${PORT}`));

クライアント側

socket.io-clientを使うとすぐにできました。

socket.io-emitterを調べててハマりましたが、socket.io-client

npm i --save socket.io-client
server_client.js
'use strict';

const io = require('socket.io-client');
const socket = io('localhost:3000');

socket.on('connect', () => {
    socket.emit("message", 'send message.');

    socket.on('chat message', (msg) => {
        // io.emit('chat message', msg);
        console.log(`message: ${msg}`);
    });
});

実行

ブラウザのチャットクライアントでメッセージを打ち込むとserver_client.js側にも通知がいきます。

おわりに

MilkcocoaとかFirebaseが使えるならそれでいいと思いますが、BaaS系は今回みたいに不安定なときもあるのでこういうのもおぼえておくといいかも

13
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
17