diff --git a/source/simple_socketio.ts b/source/simple_socketio.ts index 9e288b2..c7d990a 100644 --- a/source/simple_socketio.ts +++ b/source/simple_socketio.ts @@ -201,10 +201,17 @@ export default class SimpleSocketIOClient { } /** * Handles WebSocket messages + * The messages are a version of the socket.io message protocol + * from before v1. The messages are formatted with the first character + * being an number, the packet type (see PACKET_TYPES const for available types). + * It is followed by two or three colons depending on if the packet type has data + * or not. For example heartbeat, "2::", does not contain data, while message, "3:::Hello", does. + * * @private */ private handleMessage(event: MessageEvent): void { - const [packetType, data] = event.data.split(/:::?/); + const packetType = event.data[0]; // Get the first character of the message, the packet type + const data = event.data.replace(/^\d:::?/, ""); // Remove the packet type and the : that split message parts. if (packetType === PACKET_TYPES.event) { const parsedData = JSON.parse(data) as Payload; const { name, args } = parsedData; diff --git a/test/simple_socketio.test.js b/test/simple_socketio.test.js index 96a6e17..ed54dc1 100644 --- a/test/simple_socketio.test.js +++ b/test/simple_socketio.test.js @@ -225,6 +225,18 @@ describe("Tests using SimpleSocketIOClient", () => { expect(client.handleEvent).toHaveBeenCalledWith(eventName, eventData); }); + test("handleMessage correctly handles data with '::' in it", () => { + const eventName = "testEvent"; + const eventData = { foo: "::bar" }; + const packetData = JSON.stringify({ name: eventName, args: [eventData] }); + + vi.spyOn(client, "handleEvent"); + + client.handleMessage({ data: `${PACKET_TYPES.event}:::${packetData}` }); + + expect(client.handleEvent).toHaveBeenCalledWith(eventName, eventData); + }); + test("handleMessage correctly handles heartbeat packet type", () => { client.webSocket = createWebSocketMock();