WebSockets & Real-Time Communication
What are the best practices for implementing WebSocket subprotocols?
const protocols = ['json', 'xml'];
const ws = new WebSocket('ws://example.com', protocols);
ws.onopen = (event) => {
console.log('Connected using:', ws.protocol);
};
// Using the agreed protocol
if (ws.protocol === 'json') {
ws.send(JSON.stringify({ type: 'message', content: 'Hello' }));
} else if (ws.protocol === 'xml') {
ws.send('<message><content>Hello</content></message>');
}