Skip to main content

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

  1. Prepare the data to be sent
  2. Determine frame type (Text or Binary)
  3. If client, generate masking key and mask data
  4. Construct WebSocket frame
  5. 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:

  1. Read frame header
  2. Validate frame format
  3. If masked, unmask the data
  4. Process frame according to Opcode
  5. If fragmented message, reassemble message
  6. 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);
}
};