0Pricing
JavaScript Academy · Lesson

Sending and Receiving Messages

Exchange data with send and onmessage.

Sending and Receiving Messages is a free JavaScript Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Sending Text

Once open, socket.send(string) transmits a text message to the server.

socket.onopen = () => {
  socket.send("ping");
};

Receiving with onmessage

onmessage fires for every incoming frame. The data is on event.data.

socket.onmessage = (event) => {
  console.log("Received:", event.data);
};

JSON Framing

WebSockets carry raw strings. To send structured data, serialize with JSON.stringify and parse on receipt.

socket.send(JSON.stringify({ type: "chat", text: "hi" }));
socket.onmessage = (e) => {
  const msg = JSON.parse(e.data);
  console.log(msg.type, msg.text);
};

Message Type Routing

A common pattern: include a type field and dispatch on it.

socket.onmessage = (e) => {
  const msg = JSON.parse(e.data);
  switch (msg.type) {
    case "chat": showChat(msg); break;
    case "presence": updatePresence(msg); break;
  }
};

Sending Binary Data

send also accepts ArrayBuffer, typed arrays, and Blob for binary payloads.

const bytes = new Uint8Array([1, 2, 3, 4]);
socket.send(bytes.buffer);

Receiving Binary

With binaryType = "arraybuffer", event.data is an ArrayBuffer you can wrap in a typed array.

socket.binaryType = "arraybuffer";
socket.onmessage = (e) => {
  if (e.data instanceof ArrayBuffer) {
    const view = new Uint8Array(e.data);
    console.log(view.length);
  }
};

Backpressure with bufferedAmount

bufferedAmount reports bytes queued but not yet sent. Check it before flooding the socket to avoid unbounded memory growth.

if (socket.bufferedAmount < 1_000_000) {
  socket.send(payload);
}

Heartbeats

Send periodic ping messages so both sides know the connection is alive and intermediaries do not close idle connections.

setInterval(() => {
  if (socket.readyState === WebSocket.OPEN) {
    socket.send(JSON.stringify({ type: "ping" }));
  }
}, 30000);

Request/Response over WebSocket

Tag outgoing messages with an id and resolve a pending promise when the matching reply arrives.

const pending = new Map();
function request(payload) {
  const id = crypto.randomUUID();
  socket.send(JSON.stringify({ id, ...payload }));
  return new Promise((res) => pending.set(id, res));
}
socket.onmessage = (e) => {
  const msg = JSON.parse(e.data);
  if (pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); }
};

Queuing Before Open

If you might send before the socket opens, buffer messages and flush them in onopen.

const queue = [];
function safeSend(data) {
  if (socket.readyState === WebSocket.OPEN) socket.send(data);
  else queue.push(data);
}
socket.onopen = () => { queue.forEach((d) => socket.send(d)); queue.length = 0; };

Validating Incoming Data

Never trust the wire. Wrap JSON.parse in try/catch and validate shape before use.

socket.onmessage = (e) => {
  let msg;
  try { msg = JSON.parse(e.data); }
  catch { return; }
  if (typeof msg.type !== "string") return;
  handle(msg);
};

Quick Check

Test messaging.

Recap: Sending and Receiving

You sent text and binary, handled onmessage, framed data as JSON, routed by type, watched bufferedAmount for backpressure, added heartbeats, and queued messages before the socket opened. Next: the connection lifecycle.

Frequently asked questions

Is the “Sending and Receiving Messages” lesson free?

Yes — the full text of “Sending and Receiving Messages” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Sending and Receiving Messages”?

Exchange data with send and onmessage. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start JavaScript Academy?

No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Sending and Receiving Messages” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this JavaScript Academy lesson?

Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Opening a WebSocket Connection
  2. Sending and Receiving Messages
  3. Connection Lifecycle and Errors
  4. Reconnection Strategies
← Back to JavaScript Academy