Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for WebSocket #9

Closed
bfreis opened this issue Jul 8, 2017 · 0 comments
Closed

Add support for WebSocket #9

bfreis opened this issue Jul 8, 2017 · 0 comments

Comments

@bfreis
Copy link

bfreis commented Jul 8, 2017

Hello,

A while ago I forked the browser-based CometD JS client to add support to NodeJS, with WebSocket. My general approach is very similar to what you have here: I defined window.setTimeout & friends, but I did a bit more of a hack-y solution regarding the window.location and document objects - it works perfectly well for my specific purposes. But I'm glad to see it officially done/supported now!

I actually build an "isomorphic" solution - that is, it works both on the browser and in NodeJS.

The code to support WebSocket in node is actually very simple. All you have to do is npm install --save ws, and then in the code simply add:

window.WebSocket = require('ws')

As a "nice to have", in case you want to make this isomorphic (yay!), here's how that can be accomplished:

package.json:

{
  ...
  "dependencies": {
    "ws": "^2.2.1"
  },
  "browser": {
    "ws": false,
    "./ws-wrapper.js": "./ws-wrapper-browser.js"
  }
  ...
}

ws-wrapper.js:

module.exports = require('ws')

ws-wrapper-browser.js

module.exports = WebSocket

That's it, done. The main code does require('./ws-wrapper.js'). In NodeJS, it resolves to the real ws-wrapper.js file which, in turn, requires the real ws module.

In a packer for a Web-based, the packer reads the "browser": {...} key in package.json and performs the replacement: when it see require('./ws-wrapper.js'), it actually reads the ws-wrapper-browser.js file. The "ws": false key is useful to prevent browser packing tools from even trying to import and include in the bundle the ws dependency, because that would completely break the browser-based build.

The solution works on Node, on the Browser, and even in React Native running on a mobile phone!

Would be awesome if you could add this - or at least the trivial support for WebSocket in node, without the isomorphic feature.

Thanks!
Bruno

Hunga1 added a commit to Hunga1/cometd-nodejs-client that referenced this issue Sep 13, 2018
Adds WebSocket support for the client using the ws package.
@sbordet sbordet closed this as completed in 9816477 Nov 5, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant