Guest User

Untitled

a guest
Oct 23rd, 2019
96
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2. * tcp socket programming (client-side)
  3. * @author shj
  4. */
  5.  
  6. // import module
  7. const net = require('net');
  8.  
  9. // create TCP socket
  10. const client = new net.Socket();
  11.  
  12. // try make a connection to server (target: 127.0.0.1, port: 8888)
  13. client.connect({ port: 8888, host: '127.0.0.1' }, () => { // when connected
  14. // print message
  15. console.log('connected to server');
  16.  
  17. // send message to server
  18. client.write('hello server');
  19.  
  20. // when server sends a message
  21. client.on('data', (chunk) => {
  22. // print message
  23. console.log('client got a message >> ', chunk.toString());
  24. });
  25.  
  26. // when connection is over
  27. client.on('end', () => {
  28. // print message
  29. console.log('connection is over');
  30. });
  31. });
RAW Paste Data