{"size": 1641, "ext": "js", "max_stars_repo_path": "server/websocket.js", "max_stars_repo_name": "jrusev/collabowriter", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "server/websocket.js", "max_issues_repo_name": "jrusev/collabowriter", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/websocket.js", "max_forks_repo_name": "jrusev/collabowriter", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.8363636364, "max_line_length": 74, "alphanum_fraction": 0.5368677636}
'use strict';

var Duplex = require('stream').Duplex;
var WebSocketServer = require('ws').Server;

module.exports = function init(httpServer, shareServer) {

    var wss = new WebSocketServer({
        server: httpServer
    });

    // Ping clients to keep Heroku server awake
    setInterval(function () {
        var ping = {
            'ping': new Date()
        };
        var message = JSON.stringify(ping);
        for (var i in wss.clients) {
            wss.clients[i].send(message);
            console.log(message);
        }
    }, 10000);

    wss.on('connection', function (client) {
        var stream;
        stream = new Duplex({
            objectMode: true
        });
        stream._write = function (chunk, encoding, callback) {
            console.log('s->c ', chunk);
            client.send(JSON.stringify(chunk));
            return callback();
        };
        stream._read = function () {};
        stream.headers = client.upgradeReq.headers;
        stream.remoteAddress = client.upgradeReq.connection.remoteAddress;
        client.on('message', function (data) {
            console.log('c->s ', data);
            return stream.push(JSON.parse(data));
        });
        stream.on('error', function (msg) {
            return client.close(msg);
        });
        client.on('close', function (reason) {
            stream.push(null);
            stream.emit('close');
            console.log('client went away');
            return client.close(reason);
        });
        stream.on('end', function () {
            return client.close();
        });
        return shareServer.listen(stream);
    });
}