Add WebSocket.send() error handling
This commit is contained in:
parent
bad4cdac51
commit
2de33370cd
2 changed files with 28 additions and 6 deletions
|
|
@ -47,9 +47,13 @@ Bun.serve({
|
||||||
switch (msg.type) {
|
switch (msg.type) {
|
||||||
case "join": {
|
case "join": {
|
||||||
if (!isValidRoomName(msg.room)) {
|
if (!isValidRoomName(msg.room)) {
|
||||||
|
try {
|
||||||
ws.send(
|
ws.send(
|
||||||
JSON.stringify({ type: "error", message: "invalid room name" }),
|
JSON.stringify({ type: "error", message: "invalid room name" }),
|
||||||
);
|
);
|
||||||
|
} catch (err) {
|
||||||
|
console.debug("failed to send error to client:", err);
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
const session = getOrCreateSession(msg.room);
|
const session = getOrCreateSession(msg.room);
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,13 @@ export class Session {
|
||||||
this.clients.add(client);
|
this.clients.add(client);
|
||||||
// send full state to new client
|
// send full state to new client
|
||||||
const state = Y.encodeStateAsUpdate(this.doc);
|
const state = Y.encodeStateAsUpdate(this.doc);
|
||||||
|
try {
|
||||||
client.ws.send(encode({ type: "sync", data: Array.from(state) }));
|
client.ws.send(encode({ type: "sync", data: Array.from(state) }));
|
||||||
|
} catch (err) {
|
||||||
|
console.debug("failed to send sync to client, removing:", err);
|
||||||
|
this.clients.delete(client);
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.broadcastPeerCount();
|
this.broadcastPeerCount();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -37,7 +43,14 @@ export class Session {
|
||||||
// broadcast to others
|
// broadcast to others
|
||||||
for (const client of this.clients) {
|
for (const client of this.clients) {
|
||||||
if (client !== from) {
|
if (client !== from) {
|
||||||
client.ws.send(encode({ type: "update", data: Array.from(update) }));
|
try {
|
||||||
|
client.ws.send(
|
||||||
|
encode({ type: "update", data: Array.from(update) }),
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
console.debug("failed to send update to client, removing:", err);
|
||||||
|
this.clients.delete(client);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|
@ -54,7 +67,12 @@ export class Session {
|
||||||
broadcastPeerCount() {
|
broadcastPeerCount() {
|
||||||
const msg = encode({ type: "peers", count: this.clients.size });
|
const msg = encode({ type: "peers", count: this.clients.size });
|
||||||
for (const client of this.clients) {
|
for (const client of this.clients) {
|
||||||
|
try {
|
||||||
client.ws.send(msg);
|
client.ws.send(msg);
|
||||||
|
} catch (err) {
|
||||||
|
console.debug("failed to send peer count to client, removing:", err);
|
||||||
|
this.clients.delete(client);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue