visualization_server.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. var app = require('express')();
  2. var http = require('http').Server(app);
  3. var io = require('socket.io')(http);
  4. var net = require('net');
  5. var queue = []
  6. app.get('*', function(req, res) {
  7. if ( req.url == '/' ) {
  8. res.sendFile(__dirname + '/visualization_server.html');
  9. } else if ( req.url.match(/\.js$/) || req.url.match(/\.html$/) ) {
  10. res.sendFile(__dirname + req.url);
  11. }
  12. });
  13. io.on('connection', function(socket){
  14. console.log('A user connected!');
  15. socket.on('message', function(msg) {
  16. queue.push(msg);
  17. })
  18. });
  19. http.listen(9696, function() {
  20. console.log('Listening for user on port 9696');
  21. });
  22. // Create a server instance, and chain the listen function to it
  23. // The function passed to net.createServer() becomes the event handler for the 'connection' event
  24. // The sock object the callback function receives UNIQUE for each connection
  25. net.createServer(function(sock) {
  26. // We have a connection - a socket object is assigned to the connection automatically
  27. console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
  28. // Add a 'data' event handler to this instance of socket
  29. sock.on('data', function(data) {
  30. String(data).split('\n').forEach(function(entry) {
  31. if (entry != '') {
  32. io.emit('msg', entry);
  33. }
  34. })
  35. });
  36. // Add a 'close' event handler to this instance of socket
  37. sock.on('close', function(data) {
  38. console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
  39. });
  40. sock.on('error', function(error) {
  41. console.log('ERROR: ');
  42. });
  43. setInterval(function() {
  44. while (true) {
  45. if (queue.length == 0) {
  46. break;
  47. }
  48. sock.write(queue.pop() + '\n');
  49. }
  50. }, 5)
  51. }).listen(9999, '127.0.0.1');
  52. console.log('Listening for simulator on localhost:9999');