3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Tesselからheroku上のサーバーにWebSocket通信する

Last updated at Posted at 2015-01-25

目的

TesselではSocket.io Clientが使えないみたいで、違う方法でWebSocket通信を試してみました。今回はTesselのWebSocket通信でサンプルがあったnodejs-websocketのnpmを利用します。

ちなみに今回知ったんですが、Socket.ioは生のWebSocketだと接続できないっぽいですね。ソースとか見てないので確信ないですが、誰かやり方知ってる人いたら教えて下さい。

参考

Attempting to use socket.io client
https://forums.tessel.io/t/attempting-to-use-socket-io-client/40

Using Websockets
https://forums.tessel.io/t/using-websockets/821

Does socket.io have raw WebSocket access like sockjs?
http://stackoverflow.com/questions/15198242/does-socket-io-have-raw-websocket-access-like-sockjs

手順

サーバー側の実装

下記のソースコードを用意しました。

nodejs-websocketとmongooseをnpm installしておきます。こんな感じだと思います。mongooseはWebSocketで受けたJSONを確認用にストアしたかったから使ってます。

$npm install nodejs-websocket --save
$npm install mongoose --save
server.js
var ws = require('nodejs-websocket');
var mongoose = require('mongoose');

var port = process.env.PORT || 8000;
var mongodb_uri = process.env.MONGOLAB_URI;

var db = mongoose.connect(mongodb_uri);

var HelloSchema = new mongoose.Schema({
     date:{type:String}
});
var Hello = db.model('hello', HelloSchema);

// Create the websocket server, provide connection callback
var server = ws.createServer(function (conn) {
  console.log('Accepted new connection...');

  // If get a binary stream is opened up
  conn.on('binary', function(stream) {
    // When we get data
    stream.on('data', function(data) {
      // Log the data
      console.log('Got data:', data.toString());

      var hello = new Hello(JSON.parse(data));
      hello.save(function(err){
          if(err){
            console.log(err);
            return;
          }
          console.log("saved");
      });

    });
  });

  conn.on("close", function (code, reason) {
      console.log("Connection closed");
  });

}).listen(port);

console.log('Listening on port', port);

MONGOLAB_URIはmongolabのサーバーのURIで、下記のような形式になっています。

mongodb://<USER>:<PASS>@xxxx.mongolab.com:49150/<SCHEMA>

herokuにデプロイ

こんな感じだったと思います。

$git init
$git add .
$git commit -m "initial commit"
$heroku craete <Application Name>
$git push heroku master

今回はWebのコンソールのほうからMONGODB_URIとPORTの2つの環境変数をセットしました。けどコマンドのほうが簡単ですね。
http://chomast.com/study/web/heroku-environment-variables.html

クライアント側の実装

client.js
var ws = require('nodejs-websocket');

// Set the binary fragmentation to 1 byte so it instantly sends anything we write to it
ws.setBinaryFragmentation(1);

// When we get a connection
var connection = ws.connect('ws://<URI>', function(err) {

  if(err){
    console.log(err);
    return;
  }
  console.log("connected");

  setInterval(function (){
    var now = new Date();
    var str = '{ "date" : "' + now + '" }';
    connection.sendBinary(new Buffer(str));
  }, 1000);

});

事前にnodejs-websocketのnpm installが必要です。

普通にローカルから一旦動作確認しておくのが吉です。

$node client.js

今回はmongolabのメッセージを見て動作確認しました。

Tesselで動かす

$tessel run client.js

動いたようです。

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?