-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver-json.js
69 lines (63 loc) · 1.67 KB
/
server-json.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
var fs = require("fs"),
WebSocket = require("ws"),
WebSocketServer = require("ws").Server;
const PORT = process.env.PORT || 8080;
var interval = 2000; // send json data every 2 seconds
var i = 1000; // no. of messages to be sent
var id;
// web socket server that sends JSON string
var wss = new WebSocketServer({ port: PORT });
wss.on("connection", function (ws) {
console.log("Client connected");
id = setInterval(function () {
if (ws.readyState === WebSocket.OPEN) {
var data = JSON.stringify(sampleJson());
console.log("Send:", data);
ws.send(data, { binary: false, mask: false });
i--;
if (i <= 0) clearInterval(id);
}
}, interval);
ws.on("message", function (message) {
console.log("Received: %s", message);
});
ws.on("close", function () {
console.log("Client disconnected");
clearInterval(id);
});
ws.on("error", function (error) {
console.log("Error: %s", error);
clearInterval(id);
});
});
// return sample JSON data
function sampleJson() {
var x, y, z, w;
// position
x = randomNo(2);
y = randomNo(2);
z = randomNo(6, 4);
var position = { x, y, z };
// rotation
x = randomFloat(0, 1);
y = randomFloat(0, 1);
z = randomFloat(0, 1);
w = randomFloat(0, 1);
var rotation = { x, y, z, w };
// scale
x = y = z = randomFloat(1.5, 0.5);
var scale = { x, y, z };
return {
position,
rotation,
scale
};
}
// return random int value. (default 1-10)
function randomNo(max = 10, min = 1) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// return random float value. (default 0-1)
function randomFloat(max = 1, min = 0) {
return Math.random() * (max - min) + min;
}