HerokuでSocket.ioアプリを動かす

  • 31
    Like
  • 0
    Comment
More than 1 year has passed since last update.

>Demo Page

websocket.gif

サンプルコード

  • 機能としてはチャットするだけ
  • HerokuでNode.jsを使ったアプリをデプロイしたい
  • Herokuでsocket.ioを使ったアプリをデプロイしたい

Client side


    var socket = io();
    // submit chat message
    $('#form-chat').submit(function(){
        socket.emit('chat message', $('#mes').val());
        $('#mes').val('');
        return false;
    });
    // submit username
    $('#form-popup').submit(function(){
        // display none
        $('#popup').css({'display':'none'});
        $('#black-overlay').css({'display':'none'});
        // socket connection
        var username = $('#username').val();
        socket.emit('show username', username);
        $('#username').val('');
        return false;
    });
    socket.on('connect', function(){
        // show user name
        socket.on('show userlist', function(userlist){
            // reset
            $('#userlist').empty();
            // show all value in array userlist
            for(var i = 0; i < userlist.length; i++){
                $('#userlist').append($('<li>').text(userlist[i]));
            }
        });
    });

        // prepend message li
    socket.on('chat message', function(msg){
        $('#messages').prepend($('<li>').text(msg));
    });
    // show user name
    socket.on('show username', function(username){
        $('#form-header').empty().append($('<h4>').text(username + ' has joined!'));
    });

Server side


/*===============================================
Web Socket
===============================================*/
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var people = [];

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

io.on('connection', function(socket){
    // show chat message
    socket.on('chat message', function(msg){
        io.emit('chat message', people[socket.id] + ' : ' + msg);
    });
    // show user name
    socket.on('show username', function(username){
        // set username into people
        people[socket.id] = username;
        // add all username in userlist
        var userlist = [];
        for(key in people){
            userlist.push(people[key]);
            console.log(userlist);
        }
        // send username to client
        io.emit('show username', username); // show username in form header
        io.emit('show userlist', userlist); // show userlist in main
    });
    // disconnect socket
    socket.on('disconnect', function(){
        console.log(people[socket.id] + ' has disconnected');
        // remove nickname from people list
        delete people[socket.id];
    });
});

開発上の注意点

Procfileを作る


web: node app.js

package.jsonを作る


{
  "name": "***",
  "version": "0.0.1",
  "scripts": {
    "start": "node app.js"
  },
  "engine": {
    "node": "v0.12.0",
    "npm": "2.12.0"
  },
  "dependencies": {
    "express": "*",
    "http": "*",
    "socket.io": "*"
  }
}

Herokuにデプロイする時

以下のようにポート番号をprocess.env.PORTのように指定してあげないとHeroku上で動かない。(当たり前ですが)


server.listen(process.env.PORT || 3000, function(){
  console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});

Deploy

基本的にここの公式ドキュメントを見れば問題なくいけると思います。


$ heroku create
$ git push heroku master
$ heroku ps:scale web=1
$ heroku open