From 4eb9f8721712a2ce5e7d9f1bbf88eca110a81e1a Mon Sep 17 00:00:00 2001 From: Asher Date: Tue, 22 Jan 2019 11:48:01 -0600 Subject: [PATCH] Fix server crashing when sending data on closing/closed socket --- packages/server/src/cli.ts | 8 +++----- packages/server/src/server.ts | 11 +++++++++-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/packages/server/src/cli.ts b/packages/server/src/cli.ts index 1622461b..bca6ee22 100644 --- a/packages/server/src/cli.ts +++ b/packages/server/src/cli.ts @@ -117,11 +117,9 @@ export class Entry extends Command { app.wss.on("connection", (ws, req) => { const id = clientId++; - ws.on("open", () => { - if (sharedProcess.state === SharedProcessState.Ready) { - sendSharedProcessReady(ws); - } - }); + if (sharedProcess.state === SharedProcessState.Ready) { + sendSharedProcessReady(ws); + } logger.info(`WebSocket opened \u001B[0m${req.url}`, field("client", id), field("ip", req.socket.remoteAddress)); diff --git a/packages/server/src/server.ts b/packages/server/src/server.ts index efae772b..4116ebc1 100644 --- a/packages/server/src/server.ts +++ b/packages/server/src/server.ts @@ -1,3 +1,4 @@ +import { field, logger } from "@coder/logger"; import { ReadWriteConnection } from "@coder/protocol"; import { Server, ServerOptions } from "@coder/protocol/src/node/server"; import { NewSessionMessage } from '@coder/protocol/src/proto'; @@ -24,13 +25,19 @@ export const createApp = (registerMiddleware?: (app: express.Application) => voi return true; }; - wss.on("connection", (ws: WebSocket, req) => { + wss.on("connection", (ws) => { const connection: ReadWriteConnection = { onMessage: (cb): void => { ws.addEventListener("message", (event) => cb(event.data)); }, close: (): void => ws.close(), - send: (data): void => ws.send(data), + send: (data): void => { + try { + ws.send(data); + } catch (error) { + logger.error(error.message, field("error", error)); + } + }, onClose: (cb): void => ws.addEventListener("close", () => cb()), };