Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 10th, 2012  |  syntax: JavaScript  |  size: 1.18 KB  |  hits: 29  |  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 = '127.0.0.1';
  4. var PORT = 6969;
  5. // Create a server instance, and chain the listen function to it
  6. // The function passed to net.createServer() becomes the event handler for the 'connection' event
  7. // The sock object the callback function receives UNIQUE for each connection
  8. net.createServer(function(sock) {
  9.    
  10.     // We have a connection - a socket object is assigned to the connection automatically
  11.     console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
  12.    
  13.     // Add a 'data' event handler to this instance of socket
  14.     sock.on('data', function(data) {
  15.        
  16.         console.log('DATA ' + sock.remoteAddress + ': ' + data);
  17.         // Write the data back to the socket, the client will receive it as data from the server
  18.         sock.write('You said "' + data + '"');
  19.                 if(data=="whatever")
  20.                 {
  21.                         console.log("You got it");
  22.                 }
  23.     });
  24.    
  25.     // Add a 'close' event handler to this instance of socket
  26.     sock.on('close', function(data) {
  27.         console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
  28.     });
  29.    
  30. }).listen(PORT, HOST);
  31.  
  32. console.log('Server listening on ' + HOST +':'+ PORT);