listen on port in javascript

To listen on a port in JavaScript, we can use the net module available in Node.js. The net module provides an asynchronous network API for creating stream-based TCP servers and clients.

Here is an example of how to create a simple TCP server that listens on port 3000:

index.tsx
const net = require('net');

const server = net.createServer((socket) => {
  console.log('client connected');

  socket.on('data', (data) => {
    console.log(`received data from client: ${data}`);
  });

  socket.on('end', () => {
    console.log('client disconnected');
  });
});

server.listen(3000, () => {
  console.log('server listening on port 3000');
});
363 chars
18 lines

In this example, we create a server using the net.createServer() method, which takes a callback function as an argument. The callback function is called whenever a new client connection is established. Inside the callback function, we can listen for incoming data from the client using the socket.on('data', ...) method, and handle the disconnection of the client using the socket.on('end', ...) method.

Finally, we call the server.listen() method to start listening on the specified port. When the server is ready to accept connections, the callback function passed to server.listen() is called.

gistlibby LogSnag