TypeScript WebSocket:创建实时应用
现代Web应用越来越需要客户端与服务器之间的即时数据传输。WebSocket技术已成为创建实时应用的标准——从聊天和通知到在线游戏和交易平台。在本文中,我们将探讨如何使用TypeScript WebSocket,并提供创建完整实时应用的代码示例。
什么是WebSocket以及为什么选择TypeScript?
WebSocket是一种协议,能够在客户端和服务器之间建立持久双向连接。与HTTP(客户端发送请求并接收响应)不同,WebSocket允许双方在任何时刻主动发起数据传输。这对于需要低延迟的实时应用来说非常理想。
TypeScript为JavaScript增加了静态类型,这对于WebSocket项目至关重要。类型有助于避免处理消息时的错误,并使代码更加可预测。例如,您可以为输入和输出消息定义接口:
interface ChatMessage { type: 'message' | 'join' | 'leave'; user: string; text?: string; timestamp: number;}
interface ServerResponse { status: 'ok' | 'error'; data?: ChatMessage; error?: string;}这种方法大大简化了代码的调试和维护。
使用TypeScript配置WebSocket服务器
我们将使用ws库来创建服务器——这是Node.js上一个流行的WebSocket实现。安装依赖:
npm init -ynpm install ws @types/ws typescript @types/nodenpx tsc --init创建文件 server.ts:
import { WebSocketServer, WebSocket } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws: WebSocket, req) => { console.log('新客户端已连接');
// 发送欢迎消息 ws.send(JSON.stringify({ type: 'system', message: '欢迎加入聊天!' }));
// 处理传入消息 ws.on('message', (data: Buffer) => { try { const message = JSON.parse(data.toString()); console.log('收到:', message);
// 向所有已连接客户端广播消息 wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify({ type: 'broadcast', user: message.user, text: message.text, timestamp: Date.now() })); } }); } catch (error) { ws.send(JSON.stringify({ type: 'error', message: '消息格式无效' })); } });
ws.on('close', () => { console.log('客户端已断开'); });});
console.log('WebSocket服务器已启动在 ws://localhost:8080');使用命令 npx ts-node server.ts 启动服务器。服务器已准备好接受连接并转发消息。
TypeScript WebSocket客户端
现在创建客户端部分。TypeScript在浏览器中运行良好,因此我们将用纯TypeScript编写客户端,然后编译成JavaScript。
文件 client.ts:
interface ChatMessage { type: string; user?: string; text?: string; message?: string; timestamp?: number;}
class WebSocketClient { private socket: WebSocket; private url: string;
constructor(url: string) { this.url = url; this.socket = new WebSocket(url);