Typescript ile Websocket uzerinden zamanli bir sekilde mesaj gondermek, message
programming, typescript, message queue, websocket, queue
import WebSocket from 'ws';
class WebSocketClient {
private ws: WebSocket;
private url: string;
private messageQueue: string[] = [];
private isSending: boolean = false;
constructor(url: string) {
this.url = url;
this.connect();
}
private connect(): void {
this.ws = new WebSocket(this.url);
this.ws.on('open', () => {
console.log('WebSocket connection established.');
this.processQueue();
});
this.ws.on('message', (data) => {
console.log('Received:', data);
});
this.ws.on('close', () => {
console.log('WebSocket connection closed.');
setTimeout(() => this.connect(), 1000); // Reconnect on close
});
this.ws.on('error', (err) => {
console.error('WebSocket error:', err);
this.ws.close();
});
}
private async processQueue(): Promise<void> {
if (this.isSending || this.messageQueue.length === 0) {
return;
}
this.isSending = true;
while (this.messageQueue.length > 0) {
const message = this.messageQueue.shift()!;
this.ws.send(message);
await new Promise(resolve => setTimeout(resolve, 100)); // Delay between messages
}
this.isSending = false;
}
public send(message: string): void {
this.messageQueue.push(message);
this.processQueue();
}
}
// Usage
const wsUrl = 'wss://api.someapi.com/ws/'; // Replace it with ur URL
const client = new BTSEWebSocketClient(wsUrl);
client.send(JSON.stringify({ event: 'subscribe', data: { channel: 'your_channel' } }));
PreviousTypescript ile npm package olusturmak ve yayinlamakNextTypescript / javascript ile date bilgisi almak
Last updated
Was this helpful?