freecoding.school100% FREE · NO SIGNUP
Input HarborISSUE #33 of 46

websockets · bidirectional channel

FormaVSCaptain Invalid Input
Forma saysWebSockets open a persistent, two-way channel so client and server can message each other in real time.

For true bidirectional, low-latency communication — chat, multiplayer, live trading — use a WebSocket. new WebSocket('wss://…') upgrades from HTTP to a persistent socket; both sides then send() and receive via onmessage at any time.

Unlike SSE, it's full-duplex and can carry binary. You manage reconnection yourself, and it needs a WebSocket server, so it can't run in this offline sandbox — but the client API is tiny.

Power-ups you unlock

Captain Invalid Input attacks — common mistakes

Boss battleWrite the client shape: open a socket, send a hello on open, log messages, and reconnect on close. (Point it at a real wss:// echo server to test.)

Example code

<!doctype html>
<html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px">
  <pre id="out">WebSocket client shape (needs a wss:// server):</pre>
  <script>
    const out = document.getElementById('out');
    // const ws = new WebSocket('wss://echo.websocket.events');
    // ws.onopen    = () => ws.send('hello');
    // ws.onmessage = e => out.textContent += '\n← ' + e.data;
    // ws.onclose   = () => out.textContent += '\n[closed — reconnect here]';
    out.textContent += '\n\nconst ws = new WebSocket(url);\nws.onopen = () => ws.send("hello");';
  </script>
</body></html>
▶ Open the interactive comic issue
‹ Server-Sent Events · One-Way PushCanvas · Pixel Manipulation ›