create a tcp server on a specific port in typescript

To create a TCP server on a specific port in TypeScript:

  1. Import the net module which provides an asynchronous network API for creating stream-based TCP or IPC servers (as well as clients).
index.ts
import * as net from 'net';
28 chars
2 lines
  1. Create a server instance using the net.createServer() method, which takes a callback to handle incoming connections.
index.ts
const server = net.createServer();
35 chars
2 lines
  1. Use the 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.ts
server.listen(portNumber, () => {
  console.log(`Server bound to port ${portNumber}`);
});
91 chars
4 lines

Replace portNumber with your desired port number.

  1. Handle incoming connections using the 'connection' event or the callback passed to the createServer() method.
index.ts
server.on('connection', (socket: net.Socket) => {
  console.log(`New client connected: ${socket.remoteAddress}:${socket.remotePort}`);
  
  socket.write('Hello Client!\r\n');
  
  socket.on('data', (data) => {
    console.log(`Received data from client: ${data}`);
    socket.write(`You said: ${data}\r\n`);
  });
  
  socket.on('end', () => {
    console.log(`Client ${socket.remoteAddress}:${socket.remotePort} disconnected`);
  });
  
  socket.on('error', (err) => {
    console.error(`Socket error: ${err}`);
  });
});
523 chars
19 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.ts
server.on('listening', () => {
  console.log('Server is now listening');
});

server.on('error', (err) => {
  console.error(`Server error: ${err}`);
});

server.on('close', () => {
  console.log('Server is now closed');
});

server.listen(portNumber);
252 chars
14 lines

gistlibby LogSnag