websockets / ws

Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js
MIT License
21.34k stars 2.3k forks source link

query: difference between ws.onmessage = handler and ws.on('message', handler) #2215

Closed DevHabaek closed 3 months ago

DevHabaek commented 3 months ago

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:

  1. Will using the ws.onmessage handler in Server instead of Client end exclusively cause any issues?
  2. What are the key differences between ws.onmessage = handler and ws.on('message', handler)?
  3. I want to directly access the message as string instead of buffer. does ws.onmessage handler work for me?

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

lpinca commented 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.

lpinca commented 3 months ago

I'm closing this as answered.