Sockets

net module

  • net
    • net.Server is used to create TCP or IPC server
    • class http.Server extends net.Server
const net = require('net');
 
const server = net.createServer((socket) => { // we get socket instance
  console.log('Client connected!');
 
  // Handle incoming data from the client
  socket.on('data', (data) => {
    console.log(`Received data from client: ${data.toString()}`);
 
    // Send a response back to the client
    socket.write(`Hello from the server!`);
  });
 
  // Handle client disconnection
  socket.on('end', () => {
    console.log('Client disconnected!');
  });
});
 
const port = 8080; // Port to listen on
 
server.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

net.Socket

  • https://nodejs.org/api/net.html
  • This class is an abstraction of a TCP socket or a streaming IPC endpoint (uses named pipes on Windows, and Unix domain sockets otherwise)
  • It is also an EventEmitter
  • A net.Socket can be created by the user and used directly to interact with a server
    • It is returned by net.createConnection() so the user can use it to talk to the server
  • It can also be created by Node.js and passed to the user when a connection is received
    • It is passed to the listeners of a ‘connection’ event emitted on a net.Server, so the user can use it to interact with the client.
  • Events:
    • lookup: after resolving DNS before connecting
    • connect: successful connection
      • connectionAttempt: connection attempt started
      • connectionAttemptFailed: connection attempt failed
      • connectionAttemptTimeout: connection attempt timeout
    • ready: when socket ready to be used after successful connection
    • data: when data is received, returns Buffer or String
    • drain: when write buffer becomes empty
    • end: when other end of the socket signals end of transmission
    • error: when error occurs
    • close: socket is fully closed
    • timeout: to notify that socket is idle, connection still needs to be closed manually

dgram.Socket

  • https://nodejs.org/api/dgram.html
  • Provides implementation of UDP sockets
  • It is also an EventEmitter
  • It is returned by dgram.createSocket() so the user can use it to talk to the server
  • Events
    • connect: successful connection
    • error: when error occurs
    • listening: when dgram.Socket is addressable and can receive data
      • after socket.bind()
      • after socket.send()
    • message: when new datagram is received
      • returns Buffer and remote info: address, family, port, size
    • close: socket is closed