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:cookies [2026-09-10 17:26] – hof | talit:web:webapps:cookies [2026-09-11 10:46] (aktuell) – [Umsetzung] hof | ||
|---|---|---|---|
| Zeile 30: | Zeile 30: | ||
| app.get('/: | app.get('/: | ||
| - | const userid | + | const gameid |
| - | let game = games[parseInt(req.params[' | + | let game = games[gameid] |
| if (game == undefined) { | if (game == undefined) { | ||
| - | game = newGame(nextGameId) | + | |
| - | | + | |
| + | | ||
| } | } | ||
| + | const userid = getUserId(req, | ||
| /* join game that is waiting for players. */ | /* join game that is waiting for players. */ | ||
| if (isWaiting(game, | if (isWaiting(game, | ||
| Zeile 49: | Zeile 51: | ||
| export function isWaiting(game, | export function isWaiting(game, | ||
| // a game is waiting if we are waiting and the player is not the first player already. | // a game is waiting if we are waiting and the player is not the first player already. | ||
| - | return game.state == " | + | return game.state == " |
| } | } | ||
| export function joinGame(game, | export function joinGame(game, | ||
| if (!isWaiting(game, | if (!isWaiting(game, | ||
| - | throw Error(" | + | throw Error(" |
| } | } | ||
| if (game.player1 == undefined) { | if (game.player1 == undefined) { | ||
| - | game.player1 = userid; | + | game.player1 = userid |
| } else { | } else { | ||
| - | game.player2 = userid; | + | game.player2 = userid |
| - | game.state = " | + | game.state = " |
| } | } | ||
| } | } | ||
| Zeile 71: | Zeile 73: | ||
| /** Make a play. Only allows the joined players to */ | /** Make a play. Only allows the joined players to */ | ||
| app.get('/: | app.get('/: | ||
| - | const userid = getUserId(req, | + | const userid = getUserId(req, |
| const game = games[parseInt(req.params[' | const game = games[parseInt(req.params[' | ||
| if (game == undefined) { | if (game == undefined) { | ||
| - | res.status(404).json(" | + | res.status(404).json(" |
| } else if (game.state != " | } else if (game.state != " | ||
| - | res.status(403).json(" | + | res.status(403).json(" |
| } else if (getCurrentPlayer(game) != userid) { | } else if (getCurrentPlayer(game) != userid) { | ||
| - | res.status(403); | + | res.status(403) |
| - | res.json(" | + | res.json(" |
| } else { | } else { | ||
| - | let column = parseInt(req.params[' | + | let column = parseInt(req.params[' |
| - | dropPiece(game, | + | dropPiece(game, |
| - | res.json(toJson(game, | + | res.json(toJson(game, |
| } | } | ||
| }) | }) | ||
| Zeile 91: | Zeile 93: | ||
| /* Returns the playerid whose turn it is. */ | /* Returns the playerid whose turn it is. */ | ||
| export function getCurrentPlayer(game) { | export function getCurrentPlayer(game) { | ||
| - | return game.next == 1 ? game.player1 : game.player2; | + | return game.next == 1 ? game.player1 : game.player2 |
| } | } | ||
| </ | </ | ||
| Zeile 101: | Zeile 103: | ||
| <code javascript connect4_server.js> | <code javascript connect4_server.js> | ||
| export function toJson(game, | export function toJson(game, | ||
| - | let copy = structuredClone(game); // make a copy | + | let copy = structuredClone(game) // make a copy |
| if (game.state == " | if (game.state == " | ||
| if (copy.player1 == userid && copy.next == 1 || copy.player2 == userid && copy.next == 2) { | if (copy.player1 == userid && copy.next == 1 || copy.player2 == userid && copy.next == 2) { | ||
| - | copy[" | + | copy[" |
| } | } | ||
| } else if (game.state == " | } else if (game.state == " | ||
| if (copy.player1 == userid && copy.next == 1 || copy.player2 == userid && copy.next == 2) { | if (copy.player1 == userid && copy.next == 1 || copy.player2 == userid && copy.next == 2) { | ||
| - | copy[" | + | copy[" |
| } | } | ||
| } | } | ||
| - | return copy; | + | return copy |
| } | } | ||
| </ | </ | ||
| - | ### Polling | + | ### Weiter |
| - | + | Wie weiss ein Spieler, dass er an der Reihe ist? Weiter geht' | |
| - | Wie erfährt | + | |
| - | + | ||
| - | 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 von handleFetch wieder einen nächsten Aufruf erzeugt. | + | |
| - | 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 | + | |
| - | + | ||
| - | 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 | + | |
| - | function sendLongPollResponses(game) { | + | |
| - | let polls = longpolls[game.id] | + | |
| - | delete longpolls[game.id] // remove | + | |
| - | 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, | + | |
| - | + | ||
| - | ### Hinweise | + | |
| - | + | ||
| - | * Die ganze Web-App mit JS & Node: https:// | + | |
| - | + | ||