|
const |
|
http = require("http"), |
|
WebSocketServer = require('websocket').server; |
|
|
|
const phone_html = ` |
|
<!DOCTYPE html> |
|
<html> |
|
<head> |
|
<title>PHONE SIDE</title> |
|
<meta charset="UTF-8"> |
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"> |
|
</head> |
|
<body> |
|
<h1> It works </h1> |
|
<script> |
|
function init() { |
|
let wsUri = document.URL.replace("http", "ws"); |
|
var websocket = new WebSocket(wsUri); |
|
|
|
function wsSend(obj) { |
|
if(websocket && (websocket.readyState == 1)) |
|
websocket.send(JSON.stringify(obj)); |
|
document.body.innerHTML = JSON.stringify(obj); |
|
} |
|
|
|
function parseOrientEvent(evt) { |
|
var ret = {}; |
|
['alpha', 'beta', 'gamma', 'absolute'].forEach(k=> ret[k] = evt[k]); |
|
return ret; |
|
} |
|
|
|
window.addEventListener("deviceorientation", evt=>wsSend({ |
|
type: 'orientation', |
|
payload: parseOrientEvent(evt) |
|
})); |
|
|
|
window.addEventListener("click", evt=>wsSend({type: 'click'})); |
|
} |
|
|
|
window.addEventListener("load", init, false); |
|
</script> |
|
</body> |
|
</html> |
|
` |
|
|
|
function http_start(port) { |
|
function onRequest(request, response) { |
|
response.writeHead(200, {'Content-Type': 'text/html'}); |
|
response.write(phone_html); |
|
response.end(); |
|
}; |
|
|
|
var server = http.createServer(onRequest).listen(port); |
|
console.log('HTTP Up'); |
|
return server; |
|
} |
|
|
|
|
|
function ws_start(server) { |
|
wsServer = new WebSocketServer({ |
|
httpServer: server |
|
}); |
|
|
|
var connections = []; |
|
wsServer.on('request', function(request) { |
|
let connection = request.accept(null, request.origin); |
|
connections.push(connection); |
|
connection.on('message', msg=>connections.forEach(c=>c.sendUTF(msg.utf8Data))); |
|
connection.on('close', function(conn) { |
|
let idx = connections.indexOf(conn); |
|
if (idx != -1) connections.splice(idx, 1); |
|
}); |
|
}); |
|
|
|
console.log('WS Up'); |
|
return wsServer; |
|
} |
|
|
|
ws_start(http_start(8980)); |