Reputation: 396
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.
Upvotes: 3
Views: 1877
Reputation: 396
In the end I used https://websockets.github.io/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) => {};
Upvotes: 4
Reputation: 1
Take a look at sockjs for SockJS-client as a JavaScript client library and SockJS-node for the server implementation. http://sockjs.org
Upvotes: 0
Reputation: 578
Depending on your specific requirements I have found Socket.io to work well for both NodeJS (using socket.io-client and browser. It does more then just WebSockets though so make sure and look into it more as it may not suit your specific purposes.
I am using it for a task queue and have been pleased with it.
Upvotes: 0