世界の測量

Sibling of "Relevant, Timely, and Accurate, " but much lighter and shorter ※自らの所属する組織の見解を示すものでない

Wouldn't it be nice if we share the control of a web map?(未完)

ウェブ地図のコントロール(中心位置&ズーム)を共有できたら素敵じゃないか(ビーチボーイズ)と思っていて、そのためにはWebSocketの技術が必要かと思って、試してみているところ。

参考とさせていただいた資料は次の通り。

作ったプログラムは次の通り。メッセージが Hello であった場合にのみ、送信元に対してメッセージを送るほか、全部コネクションにブロードキャストする。

// server.js (node.js) CC0
var http = require('http');
var WSServer = require('websocket').server;
var clientHtml = require('fs').readFileSync('client.html');
var plainHttpServer = http.createServer(function(req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(clientHtml);
}).listen(8888);

var wss = new WSServer({httpServer: plainHttpServer});
var connections = [];

wss.on('request', function(ws) {
  var websocket = ws.accept(null, ws.origin);
  connections.push(websocket);
  websocket.on('message', function(msg) {
    console.log('"' + msg.utf8Data + '" is received from ' + ws.origin);
    console.log(connections.length);
    if(msg.utf8Data === 'Hello') {
      websocket.send('sent from WebSocket Server.');
      // broadcast
      connections.forEach(function(conn, i) {
        conn.send('broadcast from WebSocket Server.');
      });
    }
  });
  websocket.on('close', function(code, desc) {
    connections = connections.filter(function(conn, i) {
      return (conn == websocket) ? false : true;
    });
    console.log('connection released: ' + code + '-' + desc + ':' + 
      connections.length);
  });
});
<!doctype html>
<html>
<!-- client.html CC0 -->
<body>
<input id='message' type='text'><button id='send'>send</button>
<div id='output'></div>
<script>
(function() {
  var ws = new WebSocket('ws://localhost:8888');
  var output = document.getElementById('output');
  var send = document.getElementById('send');
  function log(evt, msg) {
    return '<div>' + evt + ': ' + msg + '</div>';
  }
  send.addEventListener('click', function() {
    var msg = document.getElementById('message').value;
    ws.send(msg);
    output.innerHTML += log('send', msg);
  });
  ws.onmessage = function(evt) {
    output.innerHTML += log('received', evt.data);
  };
  ws.onclose = function(evt) {
    output.innerHTML += log('disconnect', evt.code + '-' + evt.type);
  };
}());
</script>
</body>
</html>

次は、こういったWebSocketsサーバをherokuあたりに上げさせてもらうことを考える。