To create a TCP server on a specific port in TypeScript:
net
module which provides an asynchronous network API for creating stream-based TCP or IPC servers (as well as clients).index.ts28 chars2 lines
net.createServer()
method, which takes a callback to handle incoming connections.index.ts35 chars2 lines
server.listen()
method to start the TCP server on a specified port. Define the port number and a callback function to handle the event once the server is listening on the specified port.index.ts91 chars4 lines
Replace portNumber
with your desired port number.
'connection'
event or the callback passed to the createServer()
method.index.ts523 chars19 lines
In this example, the server listens for incoming connections and logs when a new client connects. It sends a welcome message to the client, and listens for incoming data. It sends a response back with the received data to the client. When the client disconnects, the server logs it. If there's an error on the socket, the server logs the error.
Note: Make sure to keep the server running in a loop to keep accepting incoming connections.
index.ts252 chars14 lines
gistlibby LogSnag