Skip to content

Websocket Client-Server Framework Spike #1198

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions fission/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,5 @@ dist-ssr
*.sw?

yarn.lock

__screenshots__
30 changes: 30 additions & 0 deletions multiplayer-spike/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
public/Downloadables
package-lock.json
bun.lockb

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

yarn.lock
252 changes: 252 additions & 0 deletions multiplayer-spike/client/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
class MultiplayerRobotClient {
constructor() {
this.ws = null;
this.clientId = null;
this.robotId = null;
this.connected = false;

this.robots = new Map();
this.worldSize = { width: 1000, height: 1000 };
this.inputs = {
forward: false,
backward: false,
left: false,
right: false,
};

this.canvas = document.getElementById("gameCanvas");
this.ctx = this.canvas.getContext("2d");

this.statusEl = document.getElementById("status");
this.playerCountEl = document.getElementById("playerCount");
this.latencyEl = document.getElementById("latency");

this.setupCanvas();
this.setupInputHandlers();
this.connect();
this.startRenderLoop();
}

connect() {
const protocol = location.protocol === "https:" ? "wss:" : "ws:";
const wsUrl = `${protocol}//${location.host}/game`;

console.log(`Connecting to ${wsUrl}...`);

try {
this.ws = new WebSocket(wsUrl);

this.ws.onopen = () => {
this.connected = true;
this.statusEl.textContent = "Connected";
console.log("Connected to game server");
};

this.ws.onmessage = (event) => {
this.handleServerMessage(event.data);
};

this.ws.onclose = () => {
this.connected = false;
this.statusEl.textContent = "Disconnected";
console.log("Disconnected from server");

setTimeout(() => {
if (!this.connected) {
console.log("Attempting to reconnect...");
this.connect();
}
}, 3000);
};

this.ws.onerror = (error) => {
console.error("WebSocket error:", error);
this.statusEl.textContent = "Error";
};
} catch (error) {
console.error("Failed to connect:", error);
this.statusEl.textContent = "Failed";
}
}

handleServerMessage(data) {
try {
const message = JSON.parse(data);

switch (message.type) {
case "init":
this.handleInit(message.data);
break;
case "worldState":
this.handleWorldState(message.data);
break;
case "robotJoined":
this.handleRobotJoined(message.data);
break;
case "robotLeft":
this.handleRobotLeft(message.data);
break;
case "ping":
this.handlePing(message.data);
break;
}
} catch (error) {
console.error("Failed to parse server message:", error);
}
}

handleInit(data) {
this.clientId = data.clientId;
this.robotId = data.robotId;
this.worldSize = data.worldSize;

data.robots.forEach((robot) => {
this.robots.set(robot.id, robot);
});

this.playerCountEl.textContent = data.robots.length;
console.log(`Initialized as robot ${this.robotId.substring(0, 8)}`);
}

handleWorldState(data) {
data.robots.forEach((robotData) => {
if (this.robots.has(robotData.id)) {
const robot = this.robots.get(robotData.id);
robot.position = robotData.position;
robot.velocity = robotData.velocity;
robot.rotation = robotData.rotation;
}
});
}

handleRobotJoined(data) {
this.robots.set(data.id, data);
this.playerCountEl.textContent = this.robots.size;
console.log(`Robot ${data.id.substring(0, 8)} joined`);
}

handleRobotLeft(data) {
this.robots.delete(data.robotId);
this.playerCountEl.textContent = this.robots.size;
console.log(`Robot ${data.robotId.substring(0, 8)} left`);
}

handlePing(data) {
this.send({
type: "pong",
data: { timestamp: data.timestamp },
});

const latency = Date.now() - data.timestamp;
this.latencyEl.textContent = latency;
}

setupInputHandlers() {
const keys = {
KeyW: "forward",
KeyS: "backward",
KeyA: "left",
KeyD: "right",
};

document.addEventListener("keydown", (e) => {
const action = keys[e.code];
if (action && !this.inputs[action]) {
this.inputs[action] = true;
this.sendInputs();
}
});

document.addEventListener("keyup", (e) => {
const action = keys[e.code];
if (action && this.inputs[action]) {
this.inputs[action] = false;
this.sendInputs();
}
});

window.addEventListener("resize", () => {
this.setupCanvas();
});
}

sendInputs() {
this.send({
type: "input",
data: { ...this.inputs },
});
}

setupCanvas() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}

startRenderLoop() {
const render = () => {
this.render();
requestAnimationFrame(render);
};
requestAnimationFrame(render);
}

render() {
this.ctx.fillStyle = "#000";
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

const myRobot = this.robots.get(this.robotId);
let offsetX = 0;
let offsetY = 0;

if (myRobot) {
offsetX = this.canvas.width / 2 - myRobot.position.x;
offsetY = this.canvas.height / 2 - myRobot.position.y;
}

this.ctx.strokeStyle = "#333";
this.ctx.lineWidth = 2;
this.ctx.strokeRect(
offsetX,
offsetY,
this.worldSize.width,
this.worldSize.height
);

for (const robot of this.robots.values()) {
this.drawRobot(robot, offsetX, offsetY);
}
}

drawRobot(robot, offsetX, offsetY) {
const isOwnRobot = robot.id === this.robotId;
const x = robot.position.x + offsetX;
const y = robot.position.y + offsetY;

this.ctx.save();
this.ctx.translate(x + 25, y + 25);
this.ctx.rotate((robot.rotation * Math.PI) / 180);

this.ctx.fillStyle = isOwnRobot ? "#ff0000" : "#00ff00";
this.ctx.fillRect(-25, -25, 50, 50);

this.ctx.fillStyle = "#fff";
this.ctx.beginPath();
this.ctx.moveTo(15, 0);
this.ctx.lineTo(-5, -8);
this.ctx.lineTo(-5, 8);
this.ctx.closePath();
this.ctx.fill();

this.ctx.restore();
}

send(message) {
if (this.connected && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(message));
}
}
}

document.addEventListener("DOMContentLoaded", () => {
window.gameClient = new MultiplayerRobotClient();
});
59 changes: 59 additions & 0 deletions multiplayer-spike/client/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Multiplayer Robot Simulator</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
font-family: monospace;
background: #222;
color: white;
overflow: hidden;
height: 100vh;
}

#gameCanvas {
background: #000;
display: block;
}

#info {
position: absolute;
top: 10px;
left: 10px;
background: rgba(0, 0, 0, 0.7);
padding: 10px;
font-size: 12px;
border: 1px solid #333;
}

#controls {
position: absolute;
bottom: 10px;
left: 10px;
background: rgba(0, 0, 0, 0.7);
padding: 10px;
font-size: 12px;
border: 1px solid #333;
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>

<div id="info">
<div>s: <span id="status">Connecting...</span></div>
<div>count: <span id="playerCount">0</span></div>
<div>ping: <span id="latency">-</span>ms</div>
</div>

<script src="client.js"></script>
</body>
</html>
26 changes: 26 additions & 0 deletions multiplayer-spike/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "synthesis-multiplayer-spike",
"version": "1.0.0",
"description": "Real-time multiplayer robot simulator spike using WebSockets",
"type": "module",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "node --watch server.js",
"client": "npx http-server client -p 8080 -o"
},
"dependencies": {
"express": "^4.18.2",
"helmet": "^8.1.0",
"uuid": "^9.0.1",
"ws": "^8.18.0"
},
"devDependencies": {
"@types/node": "^20.10.0",
"@types/uuid": "^9.0.7",
"@types/ws": "^8.5.10"
},
"engines": {
"node": ">=18.0.0"
}
}
Loading
Loading