Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

TCP Server - Nodester

By: a guest on Jul 13th, 2012  |  syntax: JavaScript  |  size: 1.21 KB  |  views: 45  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. var net = require('net');
  2.  
  3. var HOST = 'http://jello-world.nodester.com/';
  4. var PORT = process.env['app_port'] || 19749;
  5.  
  6. // Create a server instance, and chain the listen function to it
  7. // The function passed to net.createServer() becomes the event handler for the 'connection' event
  8. // The sock object the callback function receives UNIQUE for each connection
  9. net.createServer(function(sock) {
  10.    
  11.     // We have a connection - a socket object is assigned to the connection automatically
  12.     console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
  13.      // connect to database
  14.    
  15.     // Add a 'data' event handler to this instance of socket
  16.     sock.on('data', function(data) {
  17.        
  18.         console.log('DATA ' + sock.remoteAddress + ': ' + data);
  19.         // Write the data back to the socket, the client will receive it as data from the server
  20.         sock.write('You said "' + data + '"');
  21.        
  22.     });
  23.    
  24.     // Add a 'close' event handler to this instance of socket
  25.     sock.on('close', function(data) {
  26.         console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
  27.     });
  28.    
  29. }).listen(PORT, HOST);
  30.  
  31. console.log('TCP server listening on ' + HOST +':'+ PORT);