Jeff Thompson | 287a318 | 2012-11-11 18:12:20 -0800 | [diff] [blame] | 1 | var WebSocketServer = require('ws').Server; |
| 2 | var net = require('net'); |
| 3 | |
| 4 | var wss = new WebSocketServer({port:9696, host:'0.0.0.0'}); |
| 5 | |
| 6 | var MaxNumOfClients = 2; |
| 7 | |
| 8 | wss.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 | }); |