-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathposts-server.js
35 lines (29 loc) · 881 Bytes
/
posts-server.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
const posts = require('./data/posts.json');
var ws = require("nodejs-websocket");
const port = 8000;
var server = ws.createServer(function (conn) {
console.log("New connection received ");
sendPostAndWaitBeforeSendingNext(conn);
conn.on("close", function (code, reason) {
console.log("Connection closed")
});
conn.on("error", function(){
console.log("Error - Connection lost")
});
});
server.listen(port, (err) => {
console.log(`server listening on ${port}`)
});
function sendPostAndWaitBeforeSendingNext(conn) {
setTimeout(() => {
conn.sendText(JSON.stringify(getRandomPost()));
console.log("Sent a new post");
sendPostAndWaitBeforeSendingNext(conn);
}, getRandomWait());
}
function getRandomPost() {
return posts[Math.floor(Math.random() * Math.floor(500))];
}
function getRandomWait() {
return Math.floor(Math.random() * 6000);
}