Sending and Receiving Messages
Exchange data with send and onmessage.
Sending and Receiving Messages is a free JavaScript Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, and your progress syncs across the web and the CoddyKit app. The JavaScript Academy course includes 4 lessons in total.
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.
Learn JavaScript with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 59
- Lessons
- 200
Frequently Asked Questions
Is the “Sending and Receiving Messages” lesson free?
Yes — any 3 lessons of the JavaScript Academy learning path, including “Sending and Receiving Messages”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The JavaScript Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.
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
- Opening a WebSocket Connection
- Sending and Receiving Messages
- Connection Lifecycle and Errors
- Reconnection Strategies