Code example
class SoccerWebSocket {
constructor(wsToken) {
this.wsToken = wsToken;
this.ws = null;
this.subscriptions = new Set();
}
connect() {
this.ws = new WebSocket(`wss://ws.soccerfootball.info/?token=${this.wsToken}`);
this.ws.onopen = () => {
console.log('Connected to Soccer Football WebSocket');
// Resubscribe if reconnecting
this.subscriptions.forEach(sub => {
this.subscribe(sub.channel, sub.scope);
});
};
this.ws.onmessage = (event) => {
const message = JSON.parse(event.data);
this.handleMessage(message);
};
this.ws.onclose = (event) => {
console.log(`Connection closed: ${event.code} - ${event.reason}`);
if (event.code !== 1000) {
// Attempt reconnection after 5 seconds
setTimeout(() => this.connect(), 5000);
}
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
}
subscribe(channel, scope) {
const message = {
action: 'subscribe',
channel: channel,
scope: scope
};
this.ws.send(JSON.stringify(message));
this.subscriptions.add({ channel, scope });
}
unsubscribe(channel, scope) {
const message = {
action: 'unsubscribe',
channel: channel,
scope: scope
};
this.ws.send(JSON.stringify(message));
this.subscriptions.delete({ channel, scope });
}
ping() {
this.ws.send(JSON.stringify({ action: 'ping' }));
}
handleMessage(message) {
switch (message.type) {
case 'match_start':
console.log('Match started:', message.data);
break;
case 'goal':
console.log('Goal!', message.data);
break;
case 'halftime':
console.log('Halftime:', message.data);
break;
case 'match_end':
console.log('Match ended:', message.data);
break;
case 'stats_update':
console.log('Stats update:', message.data);
break;
case 'odds_update':
console.log('Odds update:', message.data);
break;
case 'pong':
console.log('Pong received');
break;
case 'subscribed':
console.log('Subscribed to:', message.channel);
break;
case 'error':
console.error('Error:', message.message);
break;
}
}
disconnect() {
if (this.ws) {
this.ws.close(1000, 'Client disconnect');
}
}
}
// Usage
const client = new SoccerWebSocket('your-websocket-token');
client.connect();
// Subscribe to all MAIN events
client.subscribe('MAIN', 'all');
// Subscribe to a specific match
client.subscribe('STATS', 'match:12345');
// Subscribe to a specific league
client.subscribe('ODDS', 'league:67890');
// Keep connection alive
setInterval(() => client.ping(), 30000);Best Practices
Last updated