javascriptnode.jsbrowserwebsocketcross-platform

NodeJS && browser cross compatible websocket client


My goal is to implement a websocket client in JavaScript with specific protocol.

This client should be platform independent. It should be able to run from NodeJS environment and from browsers as well. I know that one option is to use browserify on NodeJS packages and than use the result in browser, but I wonder if there is other more elegant sollution?

Also at the github repo of ws NodeJS package that is the most popular I think is being said that it returns global.WebSocket which has slightly different API. Can I still use it for platform independent client application?

Thanks for any reply.


Solution

  • In the end I used https://github.com/websockets/ws package for NodeJS which is compatible with browser WebSocket protocol API.

    var WebSock = global.WebSocket || global.MozWebSocket || require('ws');
    
    this.sock = new WebSock(url, this.subProtocol);
    this.sock.onopen = (evt) => {};
    this.sock.onmessage = (msg) => {};
    this.sock.onerror = (err) => {};