create a tcp server in typescript

To create a TCP server in Typescript, you first need to install the net module. You can install it using NPM by running the following command:

index.ts
npm install net
16 chars
2 lines

After that, create a file called server.ts and add the following code:

index.ts
import * as net from 'net';

const port = 8080;

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

  socket.on('data', (data) => {
    console.log(`Received data: ${data.toString()}`);
    socket.write(`You said: ${data}`);
  });

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

server.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});
424 chars
21 lines

In this code, we first import the net module. We then define a constant port, which specifies the port that the server will listen on.

Next, we create a net.Server instance using the net.createServer() method. This creates a new net.Server object, which allows us to listen for clients connecting on the specified port.

Whenever a new client connects to the server, the server will run the callback function passed to createServer(). This function takes a net.Socket object as its argument, which represents the client socket.

Inside this callback function, we log a message to the console indicating that a client has connected. We then set up event listeners for the socket object. Whenever the client sends data to the server, the data event is emitted. We log the incoming data to the console, and then respond to the client by writing a message back using the socket.write() method.

Whenever the client disconnects, the end event is emitted. We log a message to the console indicating that the client has disconnected.

Finally, we call the server.listen() method to start listening for incoming connections on the specified port. We log a message to the console indicating that the server is now listening on the specified port.

To run this server, we can use the tsc command to compile our Typescript code to Javascript. We can then run the resulting Javascript file using Node.js:

index.ts
tsc server.ts
node server.js
29 chars
3 lines

This sets up the server to listen for incoming connections on port 8080. You can then connect to the server from a TCP client, such as Telnet, by specifying the IP address of the machine running the server along with the specified port.

gistlibby LogSnag