unjs / crossws

🔌 Cross-platform WebSocket Servers for Node.js, Deno, Bun and Cloudflare Workers.
https://crossws.unjs.io
Other
270 stars 10 forks source link

Sending a binary message ends up as string instead of Blob or ArrayBuffer #37

Open Vahelnir opened 1 month ago

Vahelnir commented 1 month ago

Environment

crossws 0.2.4 node 20.12.2 & 18.20.2

Reproduction

https://stackblitz.com/~/github.com/Vahelnir/crossws-binary-reproduction https://github.com/Vahelnir/crossws-binary-reproduction

In this reproduction there's an alert that's triggered only when the received message is not a string. Line index.ts#14 a binary message is sent, but as you can see, the alert was never called. If you add { binary: true } though, everything's working as expected, and so the alert is triggered.###

Describe the bug

When sending some binary data, the data the client receives is a string instead of being a Blob (or an ArrayBuffer with the ws.binaryType = "arraybuffer"). Also, I couldn't reproduce it on Stackblitz, but on my macbook the connection closes with { code: 1002, reason: 'Invalid UTF-8 in text frame' }.

Edit: Forgot to add that this only applies to the adapters using ws.

Additional context

If no option is sent, the resulting options.binary is undefined. https://github.com/unjs/crossws/blob/390bca35a25db2dc153c47a7e82b2c4c878887e0/src/adapters/node.ts#L148-L155

Since ws does not check if the value is there or not before merging, we are losing the "automatic" default value. https://github.com/websockets/ws/blob/b73b11828d166e9692a9bffe9c01a7e93bab04a8/lib/websocket.js#L464-L470

If everything above is expected, or shouldn't be fixed in crossws, then it would be nice if the binary option was added to the Peer#send signature (but I don't think the other adapters would be able to do anything with it ?) https://github.com/unjs/crossws/blob/390bca35a25db2dc153c47a7e82b2c4c878887e0/src/peer.ts#L43

Let me know if I forgot anything, or if you need more details.

Logs

No response

alexzhang1030 commented 1 month ago

The same issue faced...