blob: 2b67e0d2472d91a4f0b392e952c4004bb0c23993 [file] [log] [blame]
Jeff Thompson287a3182012-11-11 18:12:20 -08001var WebSocketServer = require('ws').Server;
2var net = require('net');
3
4var wss = new WebSocketServer({port:9696, host:'0.0.0.0'});
5
6var MaxNumOfClients = 2;
7
8wss.on('connection', function(ws) {
9 console.log('WebSocket client connection received.');
10 console.log('Number of clients now is ' + wss.clients.length);
11
12 if (wss.clients.length > MaxNumOfClients) {
13 console.log('Max num of clients exceeded. Close WS connection now.');
14 ws.terminate();
15 return;
16 }
17
18 var sock_ready = false;
19 var send_queue = [];
20 var sock = net.createConnection(9695);
21
22 ws.on('message', function(message) {
23 if (typeof message == 'string')
24 console.log("Message from clinet: " + message);
25 else if (typeof message == 'object') {
26 var bytesView = new Uint8Array(message);
27
28 var logMsg = 'Byte array from client: ';
29 for (var i = 0; i < bytesView.length; i++)
30 logMsg += String.fromCharCode(bytesView[i]);
31 console.log(logMsg);
32
33 if (sock_ready) {
34 sock.write(bytesView.buffer);
35 console.log('sock.write() returned.');
36 } else {
37 send_queue.push(message);
38 }
39 }
40 });
41
42 ws.on('close', function() {
43 console.log('WebSocket connection closed.');
44 sock.end();
45 });
46
47 sock.on('connect', function() {
48 while (send_queue.length > 0) {
49 var message = send_queue.shift();
50 sock.write(message);
51 }
52 sock_ready = true;
53 console.log('ccnd socket connection ready.');
54 });
55
56 sock.on('data', function(data) {
57 if (typeof data == 'object') {
58 var bytesView = new Uint8Array(data);
59
60 console.log('Byte array from server: ');
61 var logMsg = "";
62 for (var i = 0; i < bytesView.length; i++)
63 logMsg += String.fromCharCode(bytesView[i]);
64 console.log(logMsg);
65
66 ws.send(bytesView.buffer, {binary: true, mask: false});
67 console.log('ws.send() returned.');
68 }
69 });
70
71 sock.on('end', function() {
72 console.log('TCP connection terminated by ccnd. Shut down WS connection to client.');
73 ws.terminate();
74 });
75
76 sock.on('error', function() {
77 console.log('Error on TCP connection to ccnd. Shut down WS connection to client.');
78 ws.terminate();
79 });
80});