const ENDPOINT = "http://localhost:6420"; // You'll change this after deploying your server to Rivet.const VERSION = "default"; // You'll change this after deploying your server.const rivet = new Rivet({ endpoint: ENDPOINT });
client/index.ts
Where you open a connection to your server, add:
import { Rivet } from "rivet-sdk";// Listing regions is optional. Most games integrate some sort of region selector.const regions = await rivet.lobbies.listRegions({});// Choose the first provided region. You can customize this as neededconst defaultRegion = regions.regions[0].slug;// Find a lobbylet findResponse = await rivet.lobbies.findOrCreate({ // Attempt to find a lobby with these parameters version: VERSION, regions: [defaultRegion], tags: { gameMode: "ffa" }, // Tags can be any object you want (`gameMode` is an example) players: [{}], // This creates 1 player (the empty object is the player's config) // If a lobby doesn't exist, automatically create one with this config. // // You can customize security around lobby creation in your `rivet.json`. createConfig: { region: defaultRegion, tags: { gameMode: "ffa" }, maxPlayers: 8, // Number of players allowed to join via `rivet.lobbies.find` maxPlayersDirect: 8, // Number of players allowed to join directly via `rivet.lobbies.join` },});// Build connection addresslet protocol: string;let hostname: string;let port: number;if (lobby.backend.server) { // Connecting to live server protocol = lobby.backend.server.ports["game"].protocol; hostname = lobby.backend.server.ports["game"].publicHostname; port = lobby.backend.server.ports["game"].publicPort;} else if (lobby.backend.localDevelopment) { // Connecting to local development server protocol = "http"; hostname = lobby.backend.localDevelopment.ports["game"].hostname; port = lobby.backend.localDevelopment.ports["game"].port;} else { throw new Error("unknown backend");}// Connect to server (this can be whatever networking library you're already using).//// `token` is used to securely authorize players with the matchmaker. This// helps prevent botting attacks. You'll use this in the next step.const ws = new WebSocket( `${protocol}://${hostname}:${port}?token=${players[0].token}`,);
// Used to authenticate the lobby with the Rivet API.//// These environment variables are automatically populated by Rivet. You don't// need to do anything.const LOBBY_ID = process.env.LOBBY_ID ?? "00000000-0000-0000-0000-000000000000"; const LOBBY_TOKEN = process.env.LOBBY_TOKEN;const rivet = new Rivet();// Start server (this can be whatever networking library you're already using).const wss = new WebSocketServer({ port: parseInt(process.env.PORT!) || 7777 });wss.on("connection", async (ws: WebSocket, req: any) => { // Parse token provided in the last step const searchParams = new URL(req.url!, `ws://${req.headers.host}`).searchParams; const playerToken = searchParams.get("token"); // Notify Rivet that a player disconnected ws.on("close", async () => { rivet.lobbies.setPlayerDisconnected({ lobbyId: LOBBY_ID, lobbyToken: LOBBY_TOKEN, playerTokens: [playerToken], client: ws, }) .then(() => console.log('Player disconnected')) .catch(err => console.warn("Failed to disconnect player", err)); }); // Notify Rivet that a player connected // // If the token is invalid, this function will throw an error. Abort the // connection if this happens. try { await rivet.lobbies.setPlayerConnected({ lobbyId: LOBBY_ID, lobbyToken: LOBBY_TOKEN, playerTokens: [playerToken], }); console.log('Player connected'); } catch (err) { console.warn("Failed to connect player", err); ws.close(); return; } // ...etc...});// Notify Rivet that the server can start accepting players//// Do expensive startup operations (e.g. loading maps) before calling this function.rivet.lobbies.setLobbyReady({ lobbyId: LOBBY_ID, lobbyToken: LOBBY_TOKEN }) .then(() => console.log("Lobby ready"))