Skip to content

Commit

Permalink
fix: race condition
Browse files Browse the repository at this point in the history
  • Loading branch information
djpiper28 committed May 5, 2024
1 parent 01a5d04 commit 86ab1e0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 16 deletions.
8 changes: 4 additions & 4 deletions game-source-redux/src/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@
const cube_size = 100;
onMount(() => {
KubeWebSocket.onError = (err) => {
const ws = new KubeWebSocket("Danny");
ws.onError = (err) => {
console.error(err);
};
KubeWebSocket.onClose = () => {
ws.onClose = () => {
console.error("Connection closed");
};
KubeWebSocket.connectAs("DannyBoy");
});
</script>

Expand Down
26 changes: 14 additions & 12 deletions game-source-redux/src/lib/websockets.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { v4 } from "uuid";

const baseUrl = "https://hack.djpiper28.co.uk/ws/";
const baseUrl = "wss://hack.djpiper28.co.uk/ws/";

export const ERR_VAL = -9999999;

Expand All @@ -12,7 +12,7 @@ export type PlayerCoordinateDelta = {
newCoord: Coordinate;
};

class KubeWebSocket {
export default class KubeWebSocket {
// Socket Shite
public onError: (ev: Event) => void = console.error;
public onClose: () => void = console.error;
Expand All @@ -26,12 +26,16 @@ class KubeWebSocket {
public onEmptyAction?: (coords: PlayerCoordinateDelta) => void;

private ws: WebSocket;
private name: string;

constructor(name: string) {
this.name = name;

constructor() {
this.ws = new WebSocket(baseUrl);
this.ws.onmessage = this.onMessage.bind(this);
this.ws.onclose = this.onClose.bind(this);
this.ws.onerror = this.onError.bind(this);
this.ws.onopen = this.onopen.bind(this)
}

private onMessage(event: MessageEvent) {
Expand Down Expand Up @@ -61,23 +65,21 @@ class KubeWebSocket {
}
}

public connectAs(name: string) {
private send(data: string) {
console.log(`Sending: ${data}`);
this.ws.send(data);
}

private onopen() {
const data: PlayerInfo = {
initialised: false,
player: {
uuid: v4(),
username: name,
username: this.name,
},
coordinates: [0, 0],
};

this.send(JSON.stringify(data));
}

private send(data: string) {
console.log(`Sending: ${data}`);
this.ws.send(data);
}
}

export default new KubeWebSocket();

0 comments on commit 86ab1e0

Please sign in to comment.