Closed DevHabaek closed 3 months ago
Will using the ws.onmessage handler in Server instead of Client end exclusively cause any issues?
No.
What are the key differences between ws.onmessage = handler and ws.on('message', handler)?
ws.onmessage is for the EventTarget
interface, ws.on() is for the EventEmitter
interface. With the EventEmitter
interface the listener always take a Buffer
. The second argument specifies whether the message is binary or not. In ws
The EventTarget
interface is built on top of the EventEmitter
interface.
I want to directly access the message as string instead of buffer. does ws.onmessage handler work for me?
Yes.
I'm closing this as answered.
Is there an existing issue for this?
Description
I'm currently working with the ws package to create a WebSocket server, and I've encountered some confusion regarding message handling. Specifically, I have questions about the differences between using ws.onmessage and ws.on('message', handler) to handle incoming messages.
Using ws.onmessage: When I use this approach, I'm able to directly access the message as a string via event.data. However, it appears that the message is not buffered.
Using ws.on('message', handler): With this method, the message is buffered. Consequently, in my application, I need to parse JSON messages received on the server. To achieve this, I either convert the buffer into a string and then to an object, or I parse the buffer directly using JSON.parse, which implicitly converts the buffer to a string and then to a JavaScript object.
scenario: Server will get 100k+ messages per an hour.
I have the following questions:
ws version
8.16.0
Node.js Version
v20.10.0
System
No response
Expected result
No response
Actual result
No response
Attachments
No response