Blue
Blue
CDCloudflare Developers
Created by Blue on 2/2/2024 in #workers-help
Trouble hosting websocket server
Im trying to create a websocket that just shares all the data send through it. If client A sends the data {"type":"minecraft"} to the server, all other clients recieve that data execpt for the one that send it. This is what i have so far but nothing is being recieved anywhere at all, ive tried testing using Python, Vanilla JS, Postman, NodeJS and nothing is working. any help would be amazing!
let connections = [];

addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
const upgradeHeader = request.headers.get("Upgrade");
if (!upgradeHeader || upgradeHeader !== "websocket") {
return new Response("Expected Upgrade: websocket", { status: 426 });
}

const webSocketPair = new WebSocketPair();
const client = webSocketPair[0],
server = webSocketPair[1];

connections.push(server);

server.addEventListener("message", (message) => {
connections.forEach((connection) => {
connection.send(message.data);
});
});

server.addEventListener("close", () => {
connections = connections.filter((conn) => conn !== server);
});

return new Response(null, {
status: 101,
webSocket: client,
});
}
let connections = [];

addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
const upgradeHeader = request.headers.get("Upgrade");
if (!upgradeHeader || upgradeHeader !== "websocket") {
return new Response("Expected Upgrade: websocket", { status: 426 });
}

const webSocketPair = new WebSocketPair();
const client = webSocketPair[0],
server = webSocketPair[1];

connections.push(server);

server.addEventListener("message", (message) => {
connections.forEach((connection) => {
connection.send(message.data);
});
});

server.addEventListener("close", () => {
connections = connections.filter((conn) => conn !== server);
});

return new Response(null, {
status: 101,
webSocket: client,
});
}
28 replies