Course contentsShow
← Web Development
Lesson 879 of 2,98215. Browser NetworkingFree lesson

Sending and Receiving WebSocket Messages

Transmitting text and binary data bidirectionally through WebSocket connections.

Sending and Receiving WebSocket Messages

You'll learn how to transmit text and binary data in both directions through an active WebSocket connection.

Once you've established a WebSocket connection, communication becomes a two-way street—both client and server can send messages at any time without waiting for a request.

Sending Messages from the Client

Use the send() method on your WebSocket instance to transmit data. You can send plain text strings or binary data:

const ws = new WebSocket('wss://example.com/socket');

ws.addEventListener('open', () => {
  // Send text message
  ws.send('Hello server!');
  
  // Send JSON data as text
  ws.send(JSON.stringify({ type: 'chat', message: 'Hi there' }));
  
  // Send binary data
  const buffer = new ArrayBuffer(8);
  ws.send(buffer);
});

Receiving Messages from the Server

Listen for the message event to receive incoming data. The server can push messages whenever it wants:

ws.addEventListener('message', (event) => {
  // event.data contains the message
  console.log('Received:', event.data);
  
  // If expecting JSON
  const data = JSON.parse(event.data);
  console.log('Parsed:', data);
});

Think of it like a phone conversation—once connected, either person can speak without raising their hand or waiting for permission. The send() method is speaking, and the message event is listening for the other person's voice.

Key Takeaway: WebSocket messages flow bidirectionally using send() to transmit and the message event to receive, supporting both text and binary data formats without the overhead of repeated HTTP requests.