Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Electron app

Run Funlink in Electron’s main process: it needs Node’s HTTP server and runs while windows come and go. Talk to the renderer over IPC.

This example is a device player such as FunSync Player: it drives devices through Buttplug and TCode over WebSocket, so it runs a hub for those two protocols and asks the user before connecting.

//   npm install https://github.com/FapLandPartyDev/funlink/releases/download/v0.1.0/funlink-0.1.0.tgz

import { app, BrowserWindow, ipcMain } from "electron";
import { startHub, type Peer } from "funlink";

app.whenReady().then(async () => {
  const window = new BrowserWindow();

  const hub = await startHub({
    name: "FunSync Player",
    version: app.getVersion(),
    supports: ["buttplug-ws", "tcode-ws"],
    onEvent: (event) => {
      // Offer each new app once. A `lost` event withdraws the offer.
      if (event.type === "found" && event.peer.state === "available") {
        window.webContents.send("funlink:offer", event.peer);
      }
      if (event.type === "lost") window.webContents.send("funlink:withdraw", event.peer.id);
    },
  });

  // The renderer answers the offer with "connect" or "dismiss".
  ipcMain.handle("funlink:answer", async (_event, peer: Peer, answer: "connect" | "dismiss") => {
    if (answer === "dismiss") {
      hub.setState(peer, "dismissed");
      return;
    }
    const [service] = peer.usable;
    if (!service) return;
    // Hand the endpoint to FunSync's existing connection code, for example:
    // if (service.protocol === "buttplug-ws") await connectButtplug(service.endpoint);
    // else await connectTcodeWebSocket(service.endpoint);
    hub.setState(peer, "connected");
  });

  app.on("before-quit", () => void hub.close());
});

// If FunSync later offers a service of its own, announcing it is one call:
//
//   import { announce, customProtocol } from "funlink";
//   const funlink = announce({
//     id: "funsync-player",
//     name: "FunSync Player",
//     services: [{ protocol: customProtocol("funsync", "ws"), endpoint: "ws://127.0.0.1:5123/ws" }],
//   });
//   app.on("before-quit", () => void funlink.close());

The renderer shows the offer with Connect and Not now and answers through funlink:answer. Remember Always connect choices by peer.id and connect without asking next time.

To announce from Electron instead, call announce() in the main process when your server is listening, and close() in before-quit.