sefidgaran / signalr_client

A Flutter SignalR Client for ASP.NET Core
https://pub.dev/packages/signalr_netcore
MIT License
71 stars 111 forks source link

Establish multiple hub connections and get response in parallel #62

Open GowthamanRavichandran3 opened 11 months ago

GowthamanRavichandran3 commented 11 months ago

I need to get parallel responses using signalR while uploading my documents. I began connecting hubs one by one. The first hub connection is receiving responses from signalR. Once the next hub connection is established, the previously established connections are no longer receiving responses, even though, the first connection was not closed. The connection got closed if completed or any error occurred. Kindly guide us in establishing a parallel hub connection and receiving responses in parallel.

Here's some code from what I tried. `

 List<Future> uploadApi = [];

 Future<void> uploadMultipleDocuments(List<Files> files) async {
  for (final element in event.files) {

 // Created a unique channelId for each document.
 final String uploadChannelId=_getChannelId();

 await _establishSignalRConnection(uploadChannelId, element.name);

  // After this API request, will receive data.
 uploadApi.add(_Repository.uploadDocuments());        
   }
   Future.wait(uploadApi);
 }

 Future<void> _establishSignalRConnection(String uploadChannelId, String fileName) async{
  if (hubconnection == null ||
     hubconnection.state == HubConnectionState.Disconnected) {
   await _initializeSignalR(uploadChannelId);
 }

 hubconnection.on(
  uploadChannelId,
   _uploadProgress,
       );
   }

 Future<void> _initializeSignalR(String uploadChannelId) async {
   // Configer the logging
   Logger.root.level = Level.ALL;
   final hubProtLogger = Logger('SignalR - hub');
   final transportProtLogger = Logger('SignalR - transport');

   final String cookie = 'my cookies here';

    final MessageHeaders defaultHeaders = MessageHeaders();
    //Added the headers here with cookies and other requried data.

     hubconnection = HubConnectionBuilder()
    .withUrl(myUrl,
        options: HttpConnectionOptions(
            headers: defaultHeaders,
            logger: transportProtLogger,
            requestTimeout: 3000))
    .configureLogging(hubProtLogger)
    .withAutomaticReconnect(
   retryDelays: [1000, 3000, 3000, 3000],
     ).build();

   hubconnection.onclose(
   ({error}) {
     print('[UploadSignalR]: $error');
   },
 );
    await hubconnection.start();
      }

  void _uploadProgress(List<Object> arg){ 
       //Obtained the percentage from the data received.
   final int finalPercentage = _getProgressPercentage(message);
     print('Channel ID : $uploadChannelId Current Percentage : $finalPercentage')

     if (message.toString().contains('Completed')) {
   _closeSignalRConnection(uploadChannelId);
         }     
 }

`