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.tsx363 chars18 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