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

Without a library

Any language that can send HTTP can be a peer: POST the full record to each Funlink port every 5 seconds, and ignore connection errors (no hub on that port).

  1. Create an id once and store it (a UUID). Create a random session (8–32 letters and digits) at every launch.
  2. Every 5 seconds, POST http://127.0.0.1:<port>/funlink/v1/announce with Content-Type: application/json to each port from 37420 to 37429. Use a 1-second timeout. Use 127.0.0.1, not localhost.
  3. On a clean exit, optionally POST /funlink/v1/bye with { "id": …, "session": … }.
while true; do
  for port in $(seq 37420 37429); do
    curl -sS -m 1 -X POST "http://127.0.0.1:$port/funlink/v1/announce" \
      -H 'Content-Type: application/json' \
      -d '{"id":"my-tool","session":"abcd1234","name":"My Tool","services":[{"protocol":"ofs-ws","endpoint":"ws://127.0.0.1:8080/ofs"}]}' \
      >/dev/null 2>&1 &
  done
  sleep 5
done
const record = {
  id: installId, // stored on first run
  session: crypto.randomUUID().replaceAll("-", ""),
  name: "My Tool",
  services: [{ protocol: "ofs-ws", endpoint: "ws://127.0.0.1:8080/ofs" }],
};

function announce() {
  for (let port = 37420; port <= 37429; port++) {
    fetch(`http://127.0.0.1:${port}/funlink/v1/announce`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(record),
      signal: AbortSignal.timeout(1000),
    }).catch(() => {});
  }
}

announce();
setInterval(announce, 5000);
import json, secrets, threading, time, urllib.request

record = {
    "id": install_id,  # stored on first run
    "session": secrets.token_hex(8),
    "name": "My Tool",
    "services": [{"protocol": "ofs-ws", "endpoint": "ws://127.0.0.1:8080/ofs"}],
}
body = json.dumps(record).encode()

def announce_forever():
    while True:
        for port in range(37420, 37430):
            request = urllib.request.Request(
                f"http://127.0.0.1:{port}/funlink/v1/announce",
                data=body, headers={"Content-Type": "application/json"})
            try:
                urllib.request.urlopen(request, timeout=1).close()
            except OSError:
                pass
        time.sleep(5)

threading.Thread(target=announce_forever, daemon=True).start()
// A MonoBehaviour, for example in a BepInEx plugin. Older Unity versions
// cannot reference the Funlink NuGet package, so this posts by hand.
IEnumerator Announce()
{
    var body = System.Text.Encoding.UTF8.GetBytes(recordJson);
    while (true)
    {
        for (var port = 37420; port <= 37429; port++)
        {
            var request = new UnityWebRequest($"http://127.0.0.1:{port}/funlink/v1/announce", "POST")
            {
                uploadHandler = new UploadHandlerRaw(body),
                downloadHandler = new DownloadHandlerBuffer(),
                timeout = 1,
            };
            request.SetRequestHeader("Content-Type", "application/json");
            request.SendWebRequest();   // fire and forget
        }
        yield return new WaitForSeconds(5);
    }
}
/* POSIX: announce once to every Funlink port. Call it every 5 seconds. */
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>

static const char *BODY =
    "{\"id\":\"my-tool\",\"session\":\"abcd1234\",\"name\":\"My Tool\","
    "\"services\":[{\"protocol\":\"ofs-ws\",\"endpoint\":\"ws://127.0.0.1:8080/ofs\"}]}";

void funlink_announce(void) {
  for (int port = 37420; port <= 37429; port++) {
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0) continue;
    struct timeval timeout = {1, 0};
    setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout);
    setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof timeout);
    struct sockaddr_in hub = {.sin_family = AF_INET, .sin_port = htons((uint16_t)port)};
    hub.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    if (connect(fd, (struct sockaddr *)&hub, sizeof hub) == 0) {
      char request[1024];
      int length = snprintf(request, sizeof request,
                            "POST /funlink/v1/announce HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n"
                            "Content-Type: application/json\r\nContent-Length: %zu\r\n"
                            "Connection: close\r\n\r\n%s",
                            port, strlen(BODY), BODY);
      send(fd, request, (size_t)length, 0);
      char reply[512];
      recv(fd, reply, sizeof reply, 0); /* the hub's answer, if you want it */
    }
    close(fd);
  }
}

For a Wi-Fi device, use the C library instead: it announces on the local network.

# Without the add-on: one HTTPRequest per port, every 5 seconds.
extends Node

var body := JSON.stringify({"id": "my-game", "session": "abcd1234", "name": "My Game",
	"services": [{"protocol": "ofs-ws", "endpoint": "ws://127.0.0.1:8080/ofs"}]})

func _ready() -> void:
	var timer := Timer.new()
	timer.wait_time = 5.0
	timer.timeout.connect(_announce)
	add_child(timer)
	timer.start()
	_announce()

func _announce() -> void:
	for port in range(37420, 37430):
		var request := HTTPRequest.new()
		request.timeout = 1.0
		add_child(request)
		request.request_completed.connect(func(_result, _code, _headers, _body): request.queue_free())
		if request.request("http://127.0.0.1:%d/funlink/v1/announce" % port,
				["Content-Type: application/json"], HTTPClient.METHOD_POST, body) != OK:
			request.queue_free()

The Godot add-on does this for you, with a random session, the bye and the local network.

Keep the rules in mind when you write the record by hand: field limits are in the record table, and endpoints must be on a loopback host. A hub answers 400 invalid_announce with a message that names the broken field.

Browsers: a hub may refuse web pages, and RustyFunPlayer does. Announce from a native process.