How to create channel programmatically on socketcluster?

924 Views Asked by At

I'm considering using socketcluster to build a realtime app. The docs are very clear but I could not find a way to create a channel on demand programmatically.

My need is: as a user, I would like to call a REST API which will create a channel which would immediately be up and running on the server.

For example, calling from client side: POST https://<myServer>/api/channels with JSON body { "channel": "myChannel} would create a myChannel channel on the server and my client side code would be able to subscribe directly (after having received the server response):

 var myChannel = socket.subscribe('myChannel');
 myChannel.publish('myChannel', 'I am here !');
 myChannel.watch(function (data) {
     console.log('received data from myChannel:', data);
 });

I suppose that this newly created channel would use my authorization middleware as middlewares are defined at server level (wsServer.addMiddleware(wsServer.MIDDLEWARE_SUBSCRIBE, ...)

Thanks a lot for your help,

Pierre

1

There are 1 best solutions below

0
On BEST ANSWER

With SocketCluster, channels are created and destroyed for you automatically so you don't need to manage their lifecycle. A channel will be created on the back end if there is at least one client subscribed to it (based on the channel name) and will be automatically destroyed once all of those clients have disconnected or unsubscribed from it. SC also accounts for failure cases too - E.g. if internet connections are unexpectedly lost.

SC is designed to be efficient at creating and destroying lots of unique channels on the fly. You can have hundreds of unique channels per user (so possibly many thousands or even millions of unique channels in total). Channels don't consume any CPU at all if they're idle and each channel has a tiny memory footprint.

Channels in SC are not message queues (unlike what is offered by RabbitMQ, NSQ, Kafka, Stomp...); SC does not store messages on a persistent queue (though you can extend SC with your own persistence logic).