Skip to main content
ZON shines in real-time applications like multiplayer games and trading platforms. Here is how to stream ZON packets over Socket.io.

Server (Node.js)

The key is to send the raw buffer. Socket.io handles Uint8Array natively.
server.js
const { Server } = require("socket.io");
const { serialize } = require("@zon-lib/zon");

const io = new Server(3000);

io.on("connection", (socket) => {
  console.log("Client connected");

  // Emit a binary update every second
  setInterval(() => {
    const gameState = { 
        id: "Game#1", 
        tick: Date.now() 
    };
    
    // 1. Serialize to buffer (Zero-Copy on receiver)
    const binary = serialize(gameState);
    
    // 2. Emit raw buffer
    socket.emit("update", binary);
  }, 1000);
});

Client (Browser/Node)

On the client side, we receive the buffer and wrap it instantly.
client.js
import { io } from "socket.io-client";
import { ZonReader } from "@zon-lib/zon";

const socket = io("ws://localhost:3000");

socket.on("update", (buffer) => {
  // 1. Wrap (Zero-Copy)
  // Socket.io gives us an ArrayBuffer, we need a Uint8Array
  const reader = new ZonReader(new Uint8Array(buffer));
  
  // 2. Read
  const root = reader.rootOffset;
  const id = reader.readString(root); // "Game#1"
  
  console.log("Received Update:", id);
});