Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 281
JeFf Avatar asked Aug 26 '26 06:08

JeFf


1 Answers

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) => {};
like image 75
JeFf Avatar answered Aug 28 '26 19:08

JeFf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!