ts Socket.IO 工具类
时间: 2023-07-03 19:06:44 浏览: 383
socket工具类
以下是一个简单的 TypeScript Socket.IO 工具类的示例:
```typescript
import { io, Socket } from 'socket.io-client';
export class SocketIOService {
private socket: Socket;
constructor(private url: string) {
this.socket = io(url);
}
public connect(): Promise<void> {
return new Promise((resolve, reject) => {
this.socket.on('connect', () => {
console.log(`Connected to ${this.url}`);
resolve();
});
this.socket.on('connect_error', (error: Error) => {
console.log(`Connection error: ${error.message}`);
reject(error);
});
});
}
public disconnect(): void {
this.socket.disconnect();
}
public sendMessage(event: string, data: any): void {
this.socket.emit(event, data);
}
public onMessage(event: string, callback: (data: any) => void): void {
this.socket.on(event, callback);
}
}
```
这个工具类包含了连接、断开连接、发送消息和接收消息的功能。使用时,只需要实例化一个 SocketIOService 对象并传入服务器地址,然后调用 connect() 方法来连接服务器即可。例如:
```typescript
const socketService = new SocketIOService('http://localhost:3000');
socketService.connect().then(() => {
console.log('Connected to server!');
socketService.sendMessage('hello', 'world');
socketService.onMessage('hello', (data: string) => {
console.log(`Received message: ${data}`);
});
});
```
这个例子连接到本地的 Socket.IO 服务器,发送一个消息,并且当收到名为 "hello" 的消息时输出到控制台。
阅读全文