forked from sebastianseilund/node-json-socket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexamples.js
43 lines (41 loc) · 1.32 KB
/
examples.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
var net = require('net'),
JsonSocket = require('./lib/json-socket');
var port = 9838;
var server = net.createServer();
server.listen(port);
server.on('connection', function(socket) {
socket = new JsonSocket(socket);
var n;
var isRunning = false;
var streatTimeout;
socket.on('message', function(message) {
if (message.command == 'start') {
if (!isRunning) {
n = message.beginAt;
isRunning = true;
streamInterval = setInterval(function() {
socket.sendMessage(n * n);
n++;
}, 1000);
}
} else if (message.command == 'stop') {
if (isRunning) {
isRunning = false;
clearInterval(streamInterval);
}
}
});
});
var port = 9838; //The same port that the server is listening on
var host = '127.0.0.1';
var socket = new JsonSocket(new net.Socket()); //Decorate a standard net.Socket with JsonSocket
socket.connect(port, host);
socket.on('connect', function() { //Don't send until we're connected
socket.sendMessage({command: 'start', beginAt: 10});
socket.on('message', function(square) {
console.log(square);
if (square > 200) {
socket.sendMessage({command: 'stop'});
}
});
});