test express

main
km0 2 years ago
commit ea0b273e13

1
.gitignore vendored

@ -0,0 +1 @@
node_modules/

@ -0,0 +1,57 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Draw draw draw</title>
<script src="draw.js" defer></script>
</head>
<body>
<h1>Disegna <span id="theme"></span></h1>
<div id="svg-container">
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
version="1.1"
id="svgElement"
x="0px"
y="0px"
width="500px"
height="500px"
viewBox="0 0 500 500"
enable-background="new 0 0 500 500"
xml:space="preserve"
></svg>
</div>
<button id="submit">Send</button>
<script>
const theme = document.querySelector("#theme");
const socket = new WebSocket(location.origin.replace(/^http/, "ws"));
socket.onmessage = (event) => {
let message;
try {
message = JSON.parse(event.data);
} catch (e) {}
if (message?.type == "theme") {
theme.innerHTML = message.theme;
}
};
document.querySelector("#submit").addEventListener("click", (event) => {
const paths = Array.from(document.querySelectorAll("#svgElement path")).reduce(
(accumulator, current) => {
return (accumulator += current.getAttribute("d"));
},
""
);
socket.send(paths);
return false;
});
</script>
</body>
</html>

1045
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -0,0 +1,15 @@
{
"name": "sal8",
"version": "1.0.0",
"description": "collective drawings",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"ws": "^8.11.0"
}
}

@ -0,0 +1,100 @@
// Great resource from https://stackoverflow.com/a/40700068
// Thank you ConnorFan
var strokeWidth = 4;
var bufferSize;
var svgElement = document.getElementById("svgElement");
var rect = svgElement.getBoundingClientRect();
var path = null;
var strPath;
var buffer = []; // Contains the last positions of the mouse cursor
svgElement.addEventListener("mousedown", function (e) {
bufferSize = 8;
path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("fill", "none");
path.setAttribute("stroke", "currentColor");
path.setAttribute("stroke-width", strokeWidth);
buffer = [];
var pt = getMousePosition(e);
appendToBuffer(pt);
strPath = "M" + pt.x + " " + pt.y;
path.setAttribute("d", strPath);
svgElement.appendChild(path);
});
svgElement.addEventListener("mousemove", function (e) {
if (path) {
appendToBuffer(getMousePosition(e));
updateSvgPath();
}
});
svgElement.addEventListener("mouseup", function () {
if (path) {
path = null;
}
});
svgElement.addEventListener("mouseleave", function () {
if (path) {
path = null;
}
});
var getMousePosition = function (e) {
return {
x: e.pageX - rect.left,
y: e.pageY - rect.top,
};
};
var appendToBuffer = function (pt) {
buffer.push(pt);
while (buffer.length > bufferSize) {
buffer.shift();
}
};
// Calculate the average point, starting at offset in the buffer
var getAveragePoint = function (offset) {
var len = buffer.length;
if (len % 2 === 1 || len >= bufferSize) {
var totalX = 0;
var totalY = 0;
var pt, i;
var count = 0;
for (i = offset; i < len; i++) {
count++;
pt = buffer[i];
totalX += pt.x;
totalY += pt.y;
}
return {
x: totalX / count,
y: totalY / count,
};
}
return null;
};
var updateSvgPath = function () {
var pt = getAveragePoint(0);
if (pt) {
// Get the smoothed part of the path that will not change
strPath += " L" + pt.x + " " + pt.y;
// Get the last part of the path (close to the current mouse position)
// This part will change if the mouse moves again
var tmpPath = "";
for (var offset = 2; offset < buffer.length; offset += 2) {
pt = getAveragePoint(offset);
tmpPath += " L" + pt.x + " " + pt.y;
}
// Set the complete current path coordinates
path.setAttribute("d", strPath + tmpPath);
}
};

@ -0,0 +1,71 @@
const { WebSocket, WebSocketServer } = require("ws");
const express = require("express");
const PORT = process.env.PORT || 3000;
const index = "index.html";
const server = express()
.use(express.static("public"))
.use((req, res) => res.sendFile(index, { root: __dirname }))
.listen(PORT, () => console.log(`Listening on ${PORT}`));
const wss = new WebSocketServer({ server, clientTracking: true });
let VVVV = null;
let USERS = new Set();
var theme = "";
const messageProcessor = {
default: (ws, msg) => unknownMsg(msg),
hello_v4: (ws, msg) => registerV4(ws, msg),
drawings: (ws, msg) => toV4(msg),
theme: (ws, msg) => ((theme = msg.theme), broadcast(msg)),
};
const unknownMsg = (msg) => {
console.log("❔ Unknown message type...");
console.log(msg);
};
const registerV4 = (ws, msg) => {
if (VVVV == null) console.log("⬛ vvvv client connected");
VVVV = ws;
VVVV.on("close", () => {
VVVV = null;
});
};
const toV4 = (msg) => {
if (VVVV?.readyState === WebSocket.OPEN) {
VVVV.send(JSON.stringify(msg));
}
};
const broadcast = (msg) => {
let message = JSON.stringify(msg);
for (const user of USERS.values()) {
if (user?.readyState === WebSocket.OPEN && user != VVVV) {
user.send(message);
}
}
};
wss.on("connection", (ws) => {
USERS.add(ws);
ws.send(JSON.stringify({ type: "theme", theme: theme }));
ws.on("message", (data) => {
let message;
try {
message = JSON.parse(data);
} catch (e) {}
if (message) {
(messageProcessor[message.type] || messageProcessor.default)(ws, message);
}
});
ws.on("close", () => {
USERS.delete(ws);
});
});
Loading…
Cancel
Save