 var port = 8080;
 
 var fs = require('fs');
 var options = {
 	key : fs.readFileSync('/var/cert/keys/server.key'),
  	cert : fs.readFileSync('/var/cert/certs/server.crt'),
  	requestCert : true,         /*クライアント証明書を使用しない場合はこの行をコメントアウト*/
  	rejectUnauthorized : true,  /*クライアント証明書を使用しない場合はこの行をコメントアウト*/
  	ca: fs.readFileSync('/var/cert/ca/ca.crt')
 };
 
 var server = require('https').createServer(options,function(request, response) {
     console.log((new Date()) + ' Received request for ' + request.url);
     response.writeHead(404);
     response.end();
 });
 server.listen(port, function() {
     console.log((new Date()) + ' Server is listening on port '+port);
 });
 
 var WebSocketServer = require('websocket').server;
 wsServer = new WebSocketServer({
     httpServer: server,
     autoAcceptConnections: false
 });
 
 function originIsAllowed(origin) {return true;}
 
 wsServer.on('request', function(request) {
     if (!originIsAllowed(request.origin)) {
       request.reject();
       console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
       return;
     }
    var connection = request.accept('simple-rr', request.origin);
     console.log((new Date()) + ' Connection accepted.');
     connection.on('message', function(message) {
         // 接続先個別に返信
         if (message.utf8Data != undefined) {
             // console.log('Received Message: ' + message.utf8Data);
             console.log('Received Message: ' + message.utf8Data.length);
             connection.sendUTF(message.utf8Data);
         }
         else {
             console.log('Received Binary Message: ' + message.binaryData.length);
             /*
             var s = '';
             for (var i = 0; i < message.binaryData.length; i++) {
                 if (i > 0) s += ', ';
                 s += message.binaryData[i];
             }
             console.log(s);
             */
             connection.sendBytes(message.binaryData);
         }

         // 全接続先に同じ返信
         //wsServer.broadcastUTF(message.utf8Data);
     });
     connection.on('close', function(reasonCode, description) {
         console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
     });
 });

