Network Programming in TypeScript: From Sockets to WebSocket

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Network Programming in TypeScript: From Sockets to WebSocket

\n\n

When we talk about network programming in TypeScript, we often imagine complex distributed systems, real-time chats, or game servers. And this is no coincidence: TypeScript with its strict typing and static analysis capabilities makes developing network applications not only safe but also truly convenient.

\n\n

In this article, we will explore how to create client-server applications in TypeScript using built-in Node.js modules — net and dgram — as well as libraries for working with WebSocket. You will get ready-to-use code examples that can be immediately applied in projects.

\n\n

Why TypeScript for Network Programming?

\n\n

Many developers are accustomed to using JavaScript for the backend, but TypeScript network programming offers several advantages:

\n\n
    \n
  • Data Typing — you define the structure of packets and messages in advance
  • \n
  • Autocompletion — the IDE suggests socket methods and their parameters
  • \n
  • Fewer Errors — the compiler catches type mismatches before runtime
  • \n
\n\n

Let's look at a real example. Imagine we are writing a TCP server. In JavaScript you would write:

\n\n
const server = require('net').createServer(socket => {\n  socket.on('data', data => {\n    // data — is a Buffer, need to remember this\n  });\n});
\n\n

In TypeScript, we get clear types:

\n\n
import * as net from 'net';\n\nconst server: net.Server = net.createServer((socket: net.Socket) => {\n  socket.on('data', (data: Buffer) => {\n    // Buffer type is known, work confidently\n  });\n});
\n\n

It may seem like a small thing, but on large projects this difference saves hours of debugging.

\n\n

Basics: TCP Server and Client in TypeScript

\n\n

Let's start with the classic — TCP. We'll create a simple echo server that returns to the client what it received.

\n\n

TCP Server

\n\n
import * as net from 'net';\n\nconst PORT: number = 3000;\nconst HOST: string = '127.0.0.1';\n\nconst server: net.Server = net.createServer((socket: net.Socket) => {\n  console.log(`Client connected: ${socket.remoteAddress}:${socket.remotePort}`);\n\n  socket.on('data', (data: Buffer) => {\n    const message: string = data.toString().trim();\n    console.log(`Received: ${message}`);\n    socket.write(`Echo: ${message}\\n`);\n  });\n\n  socket.on('end', () => {\n    console.log('Client disconnected');\n  });\n\n  socket.on('error', (err: Error) => {\n    console.error('Socket error:', err.message);\n  });\n});\n\nserver.listen(PORT, HOST, () => {\n  console.log(`TCP server running on ${HOST}:${PORT}`);\n});
\n\n

Notice: we typed all variables — server, socket, data, err. This allows us to see which methods are available on the socket and avoid accidental errors.

\n\n

TCP Client

\n\n
import * as net from 'net';\n\nconst client: net.Socket = new net.Socket();\n\nclient.connect(3000, '127.0.0.1', () => {\n  console.log('Connected to server');\n  client.write('Hello, server!');\n});\n\nclient.on('data', (data: Buffer) => {\n  console.log('Server response:', data.toString());\n  client.destroy();\n});\n\nclient.on('close', () => {\n  console.log('Connection closed');\n});
\n\n

This code can be run in any Node.js project with TypeScript. Just install @types/node and compile.

\n\n

UDP: When Speed Matters More Than Reliability

\n\n

If you need to transmit data without establishing a connection (for example, for streaming or games), use UDP sockets in TypeScript. The dgram module provides everything you need.

\n\n

UDP Server

\n\n
import * as dgram from 'dgram';\n\nconst server: dgram.Socke                

Blogs

Book Recommendations