Network Programming in TypeScript: From Sockets to WebSocket
\n\nWhen 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\nIn 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.
Why TypeScript for Network Programming?
\n\nMany 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
Let's look at a real example. Imagine we are writing a TCP server. In JavaScript you would write:
\n\nconst server = require('net').createServer(socket => {\n socket.on('data', data => {\n // data — is a Buffer, need to remember this\n });\n});\n\nIn TypeScript, we get clear types:
\n\nimport * 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\nIt may seem like a small thing, but on large projects this difference saves hours of debugging.
\n\nBasics: TCP Server and Client in TypeScript
\n\nLet's start with the classic — TCP. We'll create a simple echo server that returns to the client what it received.
\n\nTCP Server
\n\nimport * 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\nNotice: we typed all variables — server, socket, data, err. This allows us to see which methods are available on the socket and avoid accidental errors.
TCP Client
\n\nimport * 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\nThis code can be run in any Node.js project with TypeScript. Just install @types/node and compile.
UDP: When Speed Matters More Than Reliability
\n\nIf 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.
UDP Server
\n\nimport * as dgram from 'dgram';\n\nconst server: dgram.Socke