mexc-api
Version:
[](https://npmjs.org/package/mexc-api)
127 lines (103 loc) • 3.01 kB
text/typescript
import WebSocket from "ws";
interface Option {
url?: string
/** 日志 */
info: any
}
export class WebSocketClient {
/** 连接地址 */
private url: string;
private socket: WebSocket;
private pingIntervalId: NodeJS.Timeout | null;
private onMessageCallback: ((data: WebSocket.Data) => void) | null;
private onReadCallback: (() => void) | null;
// private info: any = null
constructor({
url = 'wss://contract.mexc.com/ws',
// info = null
}: Option) {
this.url = url;
// this.info = info
this.socket = new WebSocket(this.url);
this.pingIntervalId = null;
this.onMessageCallback = null;
this.onReadCallback = null;
this.socket.on('open', this.onOpen.bind(this));
this.socket.on('message', this._onMessage.bind(this));
this.socket.on('close', this.onClose.bind(this));
this.socket.on('error', this.onError.bind(this));
}
private log(...arg: any){
console.log(...arg)
// if(this.info){
// this.info(...arg)
// }else {
// console.log(...arg)
// }
}
private onOpen(): void {
this.log('WebSocket 连接', this.url);
this.onReadCallback?.()
// 发送心跳 ping,每隔10秒发送一次
this.pingIntervalId = setInterval(() => {
this.send({
method: "ping",
});
}, 10000);
}
private _onMessage(message: WebSocket.Data): void {
// 在这里处理接收到的消息
// 调用实例的 onMessageCallback 方法,并传递接收到的消息作为参数
if (typeof this.onMessageCallback === 'function') {
try {
const messageJson = JSON.parse(message as any)
if(messageJson.channel !== 'pong'){
this.onMessageCallback(messageJson);
}
} catch (error) {
this.log(`JSON 解析错误 ${error}`)
}
} else {
this.log(`收到消息: ${message}`);
}
}
private onClose(): void {
this.log('WebSocket 关闭');
// 清除心跳 ping 定时器
if (this.pingIntervalId !== null) {
clearInterval(this.pingIntervalId);
}
}
private onError(error: Error): void {
this.log(`WebSocket 错误: ${error.message}`);
// 清除心跳 ping 定时器
if (this.pingIntervalId !== null) {
clearInterval(this.pingIntervalId);
}
}
public send(data: any): void {
if (this.socket.readyState === WebSocket.OPEN) {
this.socket.send(JSON.stringify(data));
} else {
this.log('WebSocket is not open');
}
}
public close(): void {
this.socket.close();
}
// 设置 onMessage 回调函数
public set onMessage(callback: (data: WebSocket.Data) => void) {
if (typeof callback === 'function') {
this.onMessageCallback = callback;
} else {
this.log('Callback must be a function');
}
}
public set onRead(callback: () => void) {
if (typeof callback === 'function') {
this.onReadCallback = callback;
} else {
this.log('Callback must be a function');
}
}
}