6. Sending and Receiving Data
6.1 Sending Data
To send data over a WebSocket connection, an endpoint MUST encapsulate the data in a WebSocket frame.
Sending Steps
- Prepare the data to be sent
- Determine frame type (Text or Binary)
- If client, generate masking key and mask data
- Construct WebSocket frame
- Send through underlying TCP connection
Browser API Example
const ws = new WebSocket('wss://example.com/socket');
// Send text data
ws.send('Hello, Server!');
// Send binary data
const buffer = new ArrayBuffer(8);
ws.send(buffer);
// Send Blob
const blob = new Blob(['Hello'], { type: 'text/plain' });
ws.send(blob);
6.2 Receiving Data
When an endpoint receives data, it MUST process it following these steps:
- Read frame header
- Validate frame format
- If masked, unmask the data
- Process frame according to Opcode
- If fragmented message, reassemble message
- Deliver complete message to application layer
Browser API Example
ws.onmessage = (event) => {
if (typeof event.data === 'string') {
console.log('Received text:', event.data);
} else if (event.data instanceof ArrayBuffer) {
console.log('Received binary:', event.data);
}
};
Reference Links
- Previous Chapter: 5. Data Framing
- Next Chapter: 7. Closing the Connection