Skip to content

Commit

Permalink
implement long polling
Browse files Browse the repository at this point in the history
  • Loading branch information
PaulKreft committed Feb 19, 2024
1 parent 04199a8 commit 65b52c1
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,26 @@
import de.neuefische.paulkreft.backend.users.models.Player;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.ConcurrentLinkedQueue;

@RestController
@RequestMapping("/api/lobby")
@RequiredArgsConstructor
public class LobbyController {
private final LobbyService lobbyService;

private final ConcurrentLinkedQueue<DeferredResult<Lobby>> queuedRequests = new ConcurrentLinkedQueue<>();

@GetMapping("/long")
public DeferredResult<Lobby> getGameUpdate() {
DeferredResult<Lobby> updatedLobby = new DeferredResult<>();
updatedLobby.onTimeout(() -> queuedRequests.remove(updatedLobby));
queuedRequests.add(updatedLobby);
return updatedLobby;
}

@PostMapping
public Lobby createLobby(@RequestBody Lobby lobby) {
return lobbyService.createLobby(lobby);
Expand All @@ -26,17 +39,26 @@ public Lobby getLobbyById(@PathVariable String id) {

@PutMapping
public Lobby updateLobby(@RequestBody Lobby lobby) {
return lobbyService.updateLobby(lobby);
Lobby updatedLobby = lobbyService.updateLobby(lobby);

resolveRequest(updatedLobby);
return updatedLobby;
}

@PutMapping("/{id}/join")
public Lobby joinLobby(@PathVariable String id, @RequestBody Player player) {
return lobbyService.joinLobby(id, player);
Lobby updatedLobby = lobbyService.joinLobby(id, player);

resolveRequest(updatedLobby);
return updatedLobby;
}

@PutMapping("/{id}/leave")
public Lobby leaveLobby(@PathVariable String id, @RequestBody Player player) {
return lobbyService.leaveLobby(id, player);
Lobby updatedLobby = lobbyService.leaveLobby(id, player);

resolveRequest(updatedLobby);
return updatedLobby;
}

@DeleteMapping("/{id}")
Expand All @@ -46,11 +68,23 @@ public Lobby deleteLobby(@PathVariable String id) {

@PutMapping("/{id}/setWinner")
public Lobby setWinner(@PathVariable String id, @RequestBody ObjectNode payload) throws JsonProcessingException {
return lobbyService.setWinner(id, payload);
Lobby updatedLobby = lobbyService.setWinner(id, payload);

resolveRequest(updatedLobby);
return updatedLobby;
}

@PutMapping("/{id}/setLoser")
public Lobby setLoser(@PathVariable String id, @RequestBody Player player) {
return lobbyService.setLoser(id, player);
Lobby updatedLobby = lobbyService.setLoser(id, player);

resolveRequest(updatedLobby);
return updatedLobby;
}

public void resolveRequest(Lobby lobby) {
for (DeferredResult<Lobby> defResult : this.queuedRequests) {
defResult.setResult(lobby);
}
}
}
44 changes: 32 additions & 12 deletions frontend/src/components/MultiplayerSession.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ export const MultiplayerSession: React.FC<ActiveLobbyProps> = ({ user }) => {
const [startTime, setStartTime] = useState<number>();

useEffect(() => {
const interval = setInterval(() => {
axios.get(`/api/lobby/${id}`).then((response) => setLobby(response.data));
}, 3000);
axios.get(`/api/lobby/${id}`).then((response) => {
setLobby(response.data);
});
startListening();

return () => {
// on navigating away from the lobby component, leave the lobby
axios.put(`/api/lobby/${id}/leave`, player).then((response) => {
Expand All @@ -45,9 +47,21 @@ export const MultiplayerSession: React.FC<ActiveLobbyProps> = ({ user }) => {
.then((response) => console.log(response));
}
});
clearInterval(interval);
};
}, [id]);
}, []);

const startListening = (): void => {
axios
.get(`/api/lobby/long`)
.then((response) => {
setLobby(response.data);
startListening();
})
.catch((error) => {
console.log(error);
startListening();
});
};

useEffect(() => {
setStartTime(Date.now());
Expand Down Expand Up @@ -119,7 +133,7 @@ export const MultiplayerSession: React.FC<ActiveLobbyProps> = ({ user }) => {
let newStreakToWin: number | null = Math.abs(parseInt(event.target.value));

if (!event.target.value || event.target.value === "0") {
newStreakToWin = null;
newStreakToWin = null;
}

axios
Expand Down Expand Up @@ -154,12 +168,18 @@ export const MultiplayerSession: React.FC<ActiveLobbyProps> = ({ user }) => {
<div className="mb-16 text-5xl font-light">
<span className="font-extrabold">{lobby.winner?.name}</span> won!
</div>
<button
className="h-max items-center rounded-2xl border-2 border-black bg-black px-12 py-4 text-3xl font-light text-white hover:bg-white hover:text-black"
onClick={startGame}
>
Rematch
</button>
{lobby.host.id === player.id ? (
<button
className="h-max items-center rounded-2xl border-2 border-black bg-black px-12 py-4 text-3xl font-light text-white hover:bg-white hover:text-black"
onClick={startGame}
>
Rematch
</button>
) : (
<div className="mb-10">
<Spinner size="md" />
</div>
)}
<button
className="h-max items-center rounded-lg border-2 border-black px-3 py-1 font-light hover:bg-black hover:text-white"
onClick={backToLobby}
Expand Down

0 comments on commit 65b52c1

Please sign in to comment.