Unterschiede
Hier werden die Unterschiede zwischen zwei Versionen der Seite angezeigt.
| Beide Seiten, vorherige Überarbeitung Vorherige Überarbeitung Nächste Überarbeitung | Vorherige Überarbeitung | ||
| talit:web:webapps:clientsidejs [2026-09-10 15:22] – [Asynchronous code] hof | talit:web:webapps:clientsidejs [2026-09-10 18:52] (aktuell) – hof | ||
|---|---|---|---|
| Zeile 1: | Zeile 1: | ||
| ## Client-Side Javascript | ## Client-Side Javascript | ||
| Der Browser benötigt weiterhin Javascript für den Informationsaustausch mit dem Server. Der Click-Handler jedes Buttons soll den `set` URL aufrufen und anschliessend den Inhalt des HTMLs an den Spielzustand anpassen. | Der Browser benötigt weiterhin Javascript für den Informationsaustausch mit dem Server. Der Click-Handler jedes Buttons soll den `set` URL aufrufen und anschliessend den Inhalt des HTMLs an den Spielzustand anpassen. | ||
| + | |||
| ### Relative URLs | ### Relative URLs | ||
| - | Absolute URLs kennen wir: http:// | + | Absolute URLs kennen wir: `https:// |
| Wenn eine Webseite eine relative URL enthält, so bastelt der Browser beim Aufruf einen neuen URL aus dem der Ursprungsseite und dem relativen Pfad: | Wenn eine Webseite eine relative URL enthält, so bastelt der Browser beim Aufruf einen neuen URL aus dem der Ursprungsseite und dem relativen Pfad: | ||
| Zeile 22: | Zeile 24: | ||
| Wir werden diese Technik verwenden, um den Spielstand auf dem Server nachzuladen, | Wir werden diese Technik verwenden, um den Spielstand auf dem Server nachzuladen, | ||
| + | |||
| #### Asynchronous code | #### Asynchronous code | ||
| Zeile 39: | Zeile 42: | ||
| async function fetchGameStateFromServer() { | async function fetchGameStateFromServer() { | ||
| try { | try { | ||
| - | let response = await fetch(' | + | let response = await fetch(' |
| - | | + | |
| - | updateUi(json)); | + | updateUi(json)) |
| } catch (error) { | } catch (error) { | ||
| - | console.log(error); | + | console.log(error) |
| } | } | ||
| } | } | ||
| Zeile 52: | Zeile 55: | ||
| * '' | * '' | ||
| * Fehler können mit dem gewohnten '' | * Fehler können mit dem gewohnten '' | ||
| - | |||
| * mehr zu '' | * mehr zu '' | ||
| * [[https:// | * [[https:// | ||
| ### Umsetzung im Client-Javascript | ### Umsetzung im Client-Javascript | ||
| + | |||
| + | Unser client-side Javascript muss immer noch Click-Handler installieren. Statt direkt das Game zu verändern, ruft der Handler den entsprechenden URL auf und reflektiert anschliessend den neuen Spielzustand im HTML: | ||
| <code javascript connect4.js> | <code javascript connect4.js> | ||
| /** Updates the HTML user interface to match the given game state. */ | /** Updates the HTML user interface to match the given game state. */ | ||
| function updateHtml(grid, | function updateHtml(grid, | ||
| - | … | ||
| - | } | ||
| - | |||
| - | function updateStatus(status, | ||
| … | … | ||
| } | } | ||
| /** Drops a piece in the given column and updates the game state accordingly. */ | /** Drops a piece in the given column and updates the game state accordingly. */ | ||
| - | async function dropPiece(grid, status, column) { | + | async function dropPiece(grid, |
| // TODO: Check if move is valid. | // TODO: Check if move is valid. | ||
| - | handleFetch(grid, status, `set/ | + | handleFetch(grid, |
| } | } | ||
| - | async function handleFetch(grid, status, url) { | + | /** Fetches a game URL and updates the HTML using the new game state. */ |
| - | let response = await fetch(url); | + | async function handleFetch(grid, |
| - | let game = await response.json(); | + | let response = await fetch(url) |
| + | let game = await response.json() | ||
| // Update the HTML view. | // Update the HTML view. | ||
| - | updateHtml(grid, | + | updateHtml(grid, |
| - | // Update game status area to reflect winner / tie | + | |
| - | updateStatus(status, | + | |
| | | ||
| // TODO: fetch game state until it's our turn again. | // TODO: fetch game state until it's our turn again. | ||
| Zeile 88: | Zeile 87: | ||
| async function init() { | async function init() { | ||
| // Find the HTML game grid. | // Find the HTML game grid. | ||
| - | let grid = document.getElementsByTagName(' | + | let grid = document.getElementsByTagName(' |
| - | let status = document.getElementsByTagName(' | + | // Fetch initial |
| - | // Join a new game. | + | await handleFetch(grid, |
| - | await handleFetch(grid, status, `game`); | + | |
| // Install button click handlers for each button. | // Install button click handlers for each button. | ||
| let index = 0 | let index = 0 | ||
| for (let button of grid.getElementsByTagName(" | for (let button of grid.getElementsByTagName(" | ||
| - | const column = index % 7; | + | const column = index % 7 |
| - | button.addEventListener(" | + | button.addEventListener(" |
| - | index++; | + | index++ |
| } | } | ||
| } | } | ||
| - | init(); | + | init() |
| </ | </ | ||
| - | \\ | ||
| - | ### User Ids & Cookies | ||
| - | Um sicherzustellen, | ||
| - | <code javascript app.js> | + | ### Weiter |
| - | import express from ' | + | Jetzt sollte es möglich sein, das gleiche |
| - | import cookieParser from ' | + | |
| - | import { newGame, dropPiece, toJson, isWaiting, joinGame } from ' | + | |
| - | + | ||
| - | const app = express() | + | |
| - | app.use(cookieParser()) | + | |
| - | const port = 3001 | + | |
| - | + | ||
| - | /** Retrieve the user's identifier from the cookies, or set a new one. */ | + | |
| - | function getUserId(req, | + | |
| - | let userid = req.cookies.userid | + | |
| - | if (userid == undefined) { | + | |
| - | userid = crypto.randomUUID() | + | |
| - | res.cookie(' | + | |
| - | } | + | |
| - | return userid | + | |
| - | } | + | |
| - | + | ||
| - | /* The empty path will join a waiting game or create a fresh one. | + | |
| - | * Afterwards, the request is redirected to /:gameid/. */ | + | |
| - | app.get('', | + | |
| - | const userid = getUserId(req, | + | |
| - | // First attempt to find a waiting game and join that. | + | |
| - | for (let game of Object.values(games)) { | + | |
| - | if (isWaiting(game, | + | |
| - | joinGame(game, | + | |
| - | console.log(`Game ${game.id} randomly joined by ${userid}`) | + | |
| - | res.redirect(`${game.id}/ | + | |
| - | return | + | |
| - | } | + | |
| - | } | + | |
| - | // No waiting game found - create a new one | + | |
| - | let game = newGame(nextGameId) | + | |
| - | games[nextGameId] = game | + | |
| - | nextGameId += 1 | + | |
| - | + | ||
| - | joinGame(game, | + | |
| - | console.log(`Game ${game.id} started by ${userid}`) | + | |
| - | res.redirect(`${game.id}/ | + | |
| - | }) | + | |
| - | </ | + | |
| - | + | ||
| - | Falls ein Spieler direkt auf einen Spiel-URL geht (z.B. weil der erste Spieler den URL mit ihm geteilt hat), so muss das Spiel noch gejoint werden. Die Zustandsabfrage ändert sich also: | + | |
| - | + | ||
| - | <code javascript app.js> | + | |
| - | /** Serve the game state of any valid game id. */ | + | |
| - | app.get('/: | + | |
| - | const userid = getUserId(req, | + | |
| - | const game = games[parseInt(req.params[' | + | |
| - | if (game == undefined) { | + | |
| - | res.status(404).json(" | + | |
| - | } else { | + | |
| - | if (isWaiting(game, | + | |
| - | // Game is still waiting for a second player - join it! | + | |
| - | console.log(`Game ${game.id} directly joined by ${userid}`) | + | |
| - | joinGame(game, | + | |
| - | } | + | |
| - | res.json(toJson(game, | + | |
| - | } | + | |
| - | }) | + | |
| - | </ | + | |
| - | + | ||
| - | Damit obiger Code funktioniert, | + | |
| - | + | ||
| - | <code javascript connect4_server.js> | + | |
| - | /* Returns true if the game is waiting and userid | + | |
| - | * has not joined, false otherwise */ | + | |
| - | export function isWaiting(game, | + | |
| - | return game.state == " | + | |
| - | } | + | |
| - | + | ||
| - | /* Lets userid join the given game, throws an error if | + | |
| - | * the game cannot be joined. */ | + | |
| - | export function joinGame(game, | + | |
| - | if (!isWaiting(game, | + | |
| - | throw Error(" | + | |
| - | } | + | |
| - | if (game.player1 == undefined) { | + | |
| - | game.player1 = userid; | + | |
| - | } else { | + | |
| - | game.player2 = userid; | + | |
| - | game.state = " | + | |
| - | } | + | |
| - | } | + | |
| - | + | ||
| - | /* Returns the game state ready to be sent to the client. */ | + | |
| - | export function toJson(game, | + | |
| - | // TODO: create a copy of game using structuredClone and | + | |
| - | // set game.myturn=true if the current player is userid. | + | |
| - | return game; | + | |
| - | } | + | |
| - | </ | + | |
| - | \\ | + | |
| - | + | ||
| - | ### Sicherheit | + | |
| - | Nun können wir auch sicherstellen, dass nur ein berechtigter Spieler einen Stein setzen kann. In der `/: | + | |
| - | + | ||
| - | <code javascript app.js> | + | |
| - | /** Make a play. Only allows the joined players to */ | + | |
| - | app.get('/: | + | |
| - | const userid = getUserId(req, | + | |
| - | const game = games[parseInt(req.params[' | + | |
| - | if (game == undefined) { | + | |
| - | res.status(404).json(" | + | |
| - | } else if (game.state != " | + | |
| - | res.status(403).json(" | + | |
| - | } else if (getCurrentPlayer(game) == userid) { | + | |
| - | let column = parseInt(req.params[' | + | |
| - | dropPiece(game, | + | |
| - | res.json(toJson(game, | + | |
| - | } else { | + | |
| - | res.status(403); | + | |
| - | res.json(" | + | |
| - | } | + | |
| - | }) | + | |
| - | </ | + | |
| - | + | ||
| - | <code javascript connect4_server.js> | + | |
| - | /* Returns the playerid whose turn it is. */ | + | |
| - | export function getCurrentPlayer(game) { | + | |
| - | return game.next == 1 ? game.player1 : game.player2; | + | |
| - | } | + | |
| - | </ | + | |
| - | + | ||
| - | \\ | + | |
| - | ### Wer ist dran? | + | |
| - | + | ||
| - | Damit der Client weiss, ob er an der Reihe ist, müsste er seine eigene User-Id kennen. Wir könnten aber die Information auch einfach in das zurückgegebene JSON einbauen. Eine Möglichkeit wäre, dass wir für jede Zustandsabfrage überprüfen, | + | |
| - | + | ||
| - | <code javascript connect4_server.js> | + | |
| - | export function toJson(game, | + | |
| - | let copy = structuredClone(game); | + | |
| - | if (game.state == " | + | |
| - | if (copy.player1 == userid && copy.next == 1 || copy.player2 == userid && copy.next == 2) { | + | |
| - | copy[" | + | |
| - | } | + | |
| - | } else if (game.state == " | + | |
| - | if (copy.player1 == userid && copy.next == 1 || copy.player2 == userid && copy.next == 2) { | + | |
| - | copy[" | + | |
| - | } | + | |
| - | } | + | |
| - | return copy; | + | |
| - | } | + | |
| - | </ | + | |
| - | ### Polling | + | |
| - | + | ||
| - | Wie erfährt ein Client davon, dass der Gegenspieler ein Zug gemacht hat? Mit HTTP ist es nicht so einfach, den Client über eine Änderung des Serverzustands zu informieren. Am einfachsten ist es, wenn der Client _polling_ verwendet. Polling bedeutet, dass der Client periodisch den Server-Zustand abfrägt. | + | |
| - | + | ||
| - | Damit wir alle 500ms oder jede Sekunde den Serverzustand abfragen, bietet es sich an, wieder mit `await` zu arbeiten. Mit Promises können wir eine `async` Funktion bauen, die nebenläufig eine bestimme Zeitdauer wartet. Am Ende der `fetchUrl` Funktion rufen wir diese auf, bevor wir den Gamezustand mit einem Selbstaufruf pollen: | + | |
| - | + | ||
| - | <code javascript connect4_client.js> | + | |
| - | async function wait(ms) { | + | |
| - | // Schläft für eine Anzahl Millsekunden, | + | |
| - | return new Promise(resolve => setTimeout(resolve, | + | |
| - | } | + | |
| - | + | ||
| - | async function handleFetch(grid, | + | |
| - | let response = await fetch(url); | + | |
| - | if (response.ok) { | + | |
| - | game = await response.json(); | + | |
| - | // Update the HTML view. | + | |
| - | updateHtml(grid, | + | |
| - | // Update game status area to reflect winner / tie | + | |
| - | updateStatus(status, | + | |
| - | } | + | |
| - | // POLLING: Falls wir nicht am Zug sind, holen wir uns nach 500ms | + | |
| - | // den neuen Gamezustand. Die Rekursion (Selbstaufruf) führt dazu, dass | + | |
| - | // jeder Aufruf | + | |
| - | if (game.state == " | + | |
| - | await wait(500); | + | |
| - | await handleFetch(grid, | + | |
| - | } | + | |
| - | } | + | |
| - | </ | + | |
| - | + | ||
| - | ### Long-Polling | + | |
| - | Mit der obigen Lösung fragt jeder Client zweimal pro Sekunde nach einem Update. Polling hat zwei Nachteile: | + | |
| - | * es wird relative viel Traffic erzeugt, insbesondere, | + | |
| - | * trotzdem ist die Responsivität tief - im Mittel wartet jeder Client die Hälfte des eingestellten Delays, also 250 Millisekunden. Das ist für Vier-Gewinnt zwar ausreichend tief, aber nicht genug für Spiele mit Interaktivität. | + | |
| - | + | ||
| - | Um das zu beheben gibt es zwei Lösungsmöglichkeiten: | + | |
| - | - **Long-Polling**: | + | |
| - | - **Web-Sockets**: | + | |
| - | + | ||
| - | Hier werden wir Long-Polling anschauen. Als erstes benötigen wir eine Datenstruktur, | + | |
| - | <code javascript app.js> | + | |
| - | /** All long-poll requests by gameid. For each gameid, a list of | + | |
| - | * [response, userid] entries is stored. | + | |
| - | let longpolls = {}; | + | |
| - | </ | + | |
| - | + | ||
| - | Dazu definieren wir eine neue Route `/< | + | |
| - | + | ||
| - | <code javascript app.js> | + | |
| - | /** Serve the game state of any valid game id, but block until | + | |
| - | * the client is no longer blocked (long-polling). */ | + | |
| - | app.get('/: | + | |
| - | const userid = getUserId(req, | + | |
| - | const game = games[parseInt(req.params[' | + | |
| - | if (game == undefined) { | + | |
| - | res.status(404).json(" | + | |
| - | } else { | + | |
| - | if (isWaiting(game, | + | |
| - | console.log(`Game ${game.id} directly joined by ${userid}`) | + | |
| - | join(game, userid) | + | |
| - | res.json(toJson(game, | + | |
| - | res.end() | + | |
| - | return | + | |
| - | } | + | |
| - | // Check if userid needs to wait, then either: | + | |
| - | // - stash the [response, userid] pair for later | + | |
| - | // - instantly return actionable state | + | |
| - | if (shouldBlockRequest(game, | + | |
| - | console.log(`Stash long-poll request for ${game.id} by ${userid}`) | + | |
| - | longpolls[game.id] ??= [] | + | |
| - | longpolls[game.id].push([res, | + | |
| - | // do not end here but keep request hanging. | + | |
| - | } else { | + | |
| - | // User can act on the state, no point in waiting. | + | |
| - | res.json(toJson(game, | + | |
| - | res.end() | + | |
| - | } | + | |
| - | } | + | |
| - | }) | + | |
| - | </ | + | |
| - | + | ||
| - | Im der server-side Game-Logik implementieren wir eine neue Funktion, um zu wissen, ob ein Request blockiert werden soll oder nicht - genau dann, wenn der Zustand `" | + | |
| - | + | ||
| - | <code javascript connect4_server.js> | + | |
| - | export function shouldBlockRequest(game, | + | |
| - | return game.state == " | + | |
| - | } | + | |
| - | </ | + | |
| - | + | ||
| - | Nun benötigen wir noch die Logik, um die Long-Poll-Requests zu beantworten, | + | |
| - | + | ||
| - | <code javascript app.js> | + | |
| - | /** Sends any pending long-polling responses after a state change. */ | + | |
| - | function sendLongPollResponses(game) { | + | |
| - | let polls = longpolls[game.id] | + | |
| - | delete longpolls[game.id] | + | |
| - | if (polls) { | + | |
| - | for (let response of polls) { | + | |
| - | // a response object is a list with the actual HTTP response and the userid. | + | |
| - | let res = response[0] | + | |
| - | let userid = response[1] | + | |
| - | console.log(`End long-poll request for ${game.id} by ${userid}`) | + | |
| - | res.json(toJson(game, | + | |
| - | res.end() | + | |
| - | } | + | |
| - | } | + | |
| - | } | + | |
| - | </ | + | |
| - | + | ||
| - | Was bleibt zu tun? Der Client soll nicht mehr warten, sondern bei Bedarf das `longpoll` API benützen: | + | |
| - | + | ||
| - | <code javascript connect4_client.js> | + | |
| - | async function handleFetch(grid, | + | |
| - | let response = await fetch(url); | + | |
| - | if (response.ok) { | + | |
| - | game = await response.json(); | + | |
| - | // Update the HTML view. | + | |
| - | updateHtml(grid, | + | |
| - | // Update game status area to reflect winner / tie | + | |
| - | updateStatus(status, | + | |
| - | } | + | |
| - | if (!response.ok) { | + | |
| - | await wait(500) // wait a little if there is connection trouble | + | |
| - | } | + | |
| - | if (!response.ok || game.state == " | + | |
| - | await handleFetch(grid, | + | |
| - | } | + | |
| - | } | + | |
| - | </ | + | |
| - | Nun haben wir viel weniger Datenverkehr, | + | Hm, und wie stellen |
| - | ### Hinweise | + | Und was ist mit der Sicherheit gegenüber Dritten, die das Spiel beeinflussen könnten? |
| - | * Die ganze Web-App | + | Weiter |