HeimgardTechnologiesAS / cordova-plugin-advanced-websocket

MIT License
27 stars 18 forks source link

[Question] Connecting to multiple clients #8

Closed uzumakinaruto123 closed 5 years ago

uzumakinaruto123 commented 5 years ago

Is it possible to connect to multiple clients?

Something like:


var conn1 = new CordovaWebsocketPlugin.wsConnect({
      url: "ws://echo.websocket.org"
    }, this.receiveCallback, this.successCallback, this.failureCallback);

var conn2 = new CordovaWebsocketPlugin.wsConnect({
      url: "ws://echo.websocket.org"
    }, this.receiveCallback, this.successCallback, this.failureCallback);

or is following possible?

var conn1 = new CordovaWebsocketPlugin();
var conn2 = new CordovaWebsocketPlugin();

conn1.wsConnect({
      url: "ws://echo.websocket.org"
    }, this.receiveCallback, this.successCallback, this.failureCallback);

conn2.wsConnect({
      url: "ws://echo.websocket.org"
    }, this.receiveCallback, this.successCallback, this.failureCallback);
chax commented 5 years ago

First, sorry for late response, i saw the question right when you opened it, but i never got to answer it. Second, it is always good to first read README and then try out in the actual code, everything is explained there and should be super simple to use.

Now to simply answer the question. You can open as many WebSocket connections as you like. Your first example is closer to what you need, because you don't need to instantiate CordovaWebSocketPlugin, you just use it, and since wsConnect() method doesn't return anything, you don't store it in variable. This wsConnect() method is actually async method and you pass it your callback methods that you implement yourself, these methods will be called when WebSocket is opened successfully (successCallback) or when something fails (failureCallback) or for receiveCallback, it will be called when new message is received over WebSocket.

All three callback methods will be called with one argument which is object, always containing webSocketId property, by this autogenerated id, you can identify and handle your WebSocket. Using it you can send messages to that particular opened WebSocket, or close your WebSocket, and everytime your receiveCallback is called it will contain the same webSocketId.

If you are using it in Ionic application and you write it in TypeScript, i wrote this TypeScript class so you can use this plugin even easier. (this one you DO instantiate for every WebSocket connection you are going to create) https://gist.github.com/chax/89a3805b08c875d3065a8cf2fb301668

I hope this helps you or anyone else for that matter.

uzumakinaruto123 commented 5 years ago

Hi, Chax. I had already tried the plugin but with one connection after which I was away from work. I was just wondering about this while travelling so decided to ask a quick question. Anyways, it was my fault. Sorry about that. Thanks a lot for the detailed explanation. This can be closed. :)