Giter Club home page Giter Club logo

signalr_client's Introduction

signalr_client

pub package

A Flutter SignalR Client for ASP.NET Core.
ASP.NET Core SignalR is an open-source library that simplifies adding real-time web functionality to apps. Real-time web functionality enables server-side code to push content to clients instantly.

The client is able to invoke server side hub functions (including streaming functions) and to receive method invocations issued by the server.

The client supports the following transport protocols:

  • WebSocket
  • Service Side Events
  • Long Polling

The client supports the following hub protocols:

  • Json
  • MessagePack - Since I can't find a MessagePack library that support the current flutter version.

Examples

Getting Started

Add signalr_client to your pubspec.yaml dependencies:

...
dependencies:
  flutter:
    sdk: flutter

  signalr_client:
...

Usage

Let's demo some basic usages:

1. Create a hub connection:

// Import the library.
import 'package:signalr_client/signalr_client.dart';

// The location of the SignalR Server.
final serverUrl = "192.168.10.50:51001";
// Creates the connection by using the HubConnectionBuilder.
final hubConnection = HubConnectionBuilder().withUrl(serverUrl).build();
// When the connection is closed, print out a message to the console.
final hubConnection.onclose( (error) => print("Connection Closed"));

Logging is supported via the dart logging package:

// Import theses libraries.
import 'package:logging/logging.dart';
import 'package:signalr_client/signalr_client.dart';

// Configer the logging
Logger.root.level = Level.ALL;
// Writes the log messages to the console
Logger.root.onRecord.listen((LogRecord rec) {
  print('${rec.level.name}: ${rec.time}: ${rec.message}');
});

// If you want only to log out the message for the higer level hub protocol:
final hubProtLogger = Logger("SignalR - hub");
// If youn want to also to log out transport messages:
final transportProtLogger = Logger("SignalR - transport");

// The location of the SignalR Server.
final serverUrl = "192.168.10.50:51001";
final connectionOptions = HttpConnectionOptions
final httpOptions = new HttpConnectionOptions(logger: transportProtLogger);
//final httpOptions = new HttpConnectionOptions(logger: transportProtLogger, transport: HttpTransportType.WebSockets); // default transport type.
//final httpOptions = new HttpConnectionOptions(logger: transportProtLogger, transport: HttpTransportType.ServerSentEvents);
//final httpOptions = new HttpConnectionOptions(logger: transportProtLogger, transport: HttpTransportType.LongPolling);

// If you need to authorize the Hub connection than provide a an async callback function that returns 
// the token string (see AccessTokenFactory typdef) and assigned it to the accessTokenFactory parameter:
// final httpOptions = new HttpConnectionOptions( .... accessTokenFactory: () async => await getAccessToken() ); 

// Creates the connection by using the HubConnectionBuilder.
final hubConnection = HubConnectionBuilder().withUrl(serverUrl, options: httpOptions).configureLogging(hubProtLogger).build();
// When the connection is closed, print out a message to the console.
final hubConnection.onclose( (error) => print("Connection Closed"));

2. Connect to a Hub:

Calling following method starts handshaking and connects the client to SignalR server

await hubConnection.start();

3. Calling a Hub function:

Assuming there is this hub function:

public string MethodOneSimpleParameterSimpleReturnValue(string p1)
{
  Console.WriteLine($"'MethodOneSimpleParameterSimpleReturnValue' invoked. Parameter value: '{p1}");
  return p1;
}

The client can invoke the function by using:

  final result = await hubConnection.invoke("MethodOneSimpleParameterSimpleReturnValue", args: <Object>["ParameterValue"]);
  logger.log(LogLevel.Information, "Result: '$result");

4. Calling a client function:

Assuming the server calls a function "aClientProvidedFunction":

  await Clients.Caller.SendAsync("aClientProvidedFunction", null);

The Client provides the function like this:

  
  hubConnection.on("aClientProvidedFunction", _handleAClientProvidedFunction);

  // To unregister the function use:
  // a) to unregister a specific implementation:
  // hubConnection.off("aClientProvidedFunction", method: _handleServerInvokeMethodNoParametersNoReturnValue);
  // b) to unregister all implementations:
  // hubConnection.off("aClientProvidedFunction");
  ...
  void _handleAClientProvidedFunction(List<Object> parameters) {
    logger.log(LogLevel.Information, "Server invoked the method");
  }

A note about the parameter types

All function parameters and return values are serialized/deserialized into/from JSON by using the dart:convert package (json.endcode/json.decode). Make sure that you:

  • use only simple parameter types

or

  • use objects that implements toJson() since that method is used by the dart:convert package to serialize an object.

Flutter Json 101:

signalr_client's People

Contributors

heathhopkins avatar macromania avatar soernt avatar tvolkert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

signalr_client's Issues

connection error

hello everyone

when i call the start function
if (hubConnection.state != HubConnectionState.Connected) {
await hubConnection.start();
}
i get this issue

I/flutter (22035): FINER: 2018-11-16 19:57:32.684732: Starting HubConnection.
I/flutter (22035): FINER: 2018-11-16 19:57:32.712285: Starting connection with transfer format 'TransferFormat.Text'.
I/flutter (22035): FINER: 2018-11-16 19:57:32.727879: Sending negotiation request: http://192.168.2.1:52001/PrivateChat/negotiate
I/flutter (22035): FINEST: 2018-11-16 19:57:32.800175: HTTP send: url 'http://192.168.2.1:52001/PrivateChat/negotiate', method: 'POST' content: ''
Syncing files to device SM G532F...
I/flutter (22035): SEVERE: 2018-11-16 19:57:33.603061: Failed to complete negotiation with the server: Invalid argument(s): Response Content-Type not supported: [application/json; charset=UTF-8]
I/flutter (22035): SEVERE: 2018-11-16 19:57:33.603902: Failed to start the connection >> : Invalid argument(s): Response Content-Type not supported: [application/json; charset=UTF-8]
E/flutter (22035): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter (22035): Invalid argument(s): Response Content-Type not supported: [application/json; charset=UTF-8]
E/flutter (22035): #0 HttpConnection._startInternal (package:signalr_client/http_connection.dart:257:7)
E/flutter (22035):
E/flutter (22035): #1 HttpConnection.start (package:signalr_client/http_connection.dart:142:21)
E/flutter (22035): #2 HubConnection.start (package:signalr_client/hub_connection.dart:103:23)
E/flutter (22035):
E/flutter (22035): #3 ChatService.onCreate (package:mbrcld/services/chatService.dart:38:27)
E/flutter (22035):
E/flutter (22035): #4 main (package:mbrcld/main.dart:103:21)
E/flutter (22035):
E/flutter (22035): #5 _startIsolate. (dart:isolate/runtime/libisolate_patch.dart:289:19)
E/flutter (22035): #6 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)

Cannot start() connection to signalR server

Hello, much like others, I cannot seem to start() a connection to the signalR server. I get back the dreaded Response Content-Type not supported: [application/json; charset=UTF-8]

I looked at the code in dartio_http_client.dart and do not understand some things, specifically with block lines 85 thru 97:

final contentTypeHeader = httpResp.headers["Content-Type"];
final isJsonContent =
    contentTypeHeader.indexOf("application/json") != -1;
if (isJsonContent) {
  content = await httpResp.transform(utf8.decoder).join();
} else {
  content = await httpResp.transform(utf8.decoder).join();
  // When using SSE and the uri has an 'id' query parameter the response is not evaluated, otherwise it is an error.
  if (isStringEmpty(uri.queryParameters['id'])) {
    throw ArgumentError(
        "Response Content-Type not supported: $contentTypeHeader");
  }
}

From what I can tell, the contentTypeHeader variable holds a 'growable list', not a simple string. Thus, when trying to find the 'indexOf("application/json")' if fails (returns -1) instead of returning 0 for the start of the 1st (0th) element in that list. In other words isJsonContent should be TRUE.
image

What's future interesting is that as it stands right now, with a FALSE value, the content is still decoded properly and seems fine. However because there is no 'id' query param in the uri, the code throws the ArgumentError that several of us have hit.

So, what is the solution to this? Is this something that can be fixed?

Thank you,

-David

Not able to specify Hub in server.

For example in one of our API's we have multiple signalR hubs such as UserHub, DataHub, and Message Hub. In C# we would do something like:

var signalRConnection = new HubConnection("http://{serverUrl}"); var signalRUserProxy = signalRConnection.CreateHubProxy("UserHub"); var signalRDataProxy = signalRConnection.CreateHubProxy("DataHub"); var signalRMessageProxy = signalRConnection.CreateHubProxy("MessageHub"); signalRConnection.Start().Wait(); signalRUserProxy.On("updateUsers", x => UpdateUsers(x)); signalRDataProxy.On("updateData", x => UpdateData(x)); signalRMessageProxy.On("updateMessages", x => UpdateMessages(x));

Where each proxy represents a different Hub. I don't see how to accomplish this with the example code supplied.

Signal R Core Can't Connect when deployed to IIS

Currently I'm using my local for my flutter app to connect to Signal R Core but when I deployed my Signal R Core API to my local IIS Server it cannot connect to Signal R Core. Sometimes it connects then disconnects, but mostly disconnects. What is the possible issue of this? Thanks in advance

Run in background service

Can I use this pub in background task?
Because when I close my App, I lose my connection with the server.

Pass parameter

I need to pass Parameter(Not a token but sth like an Id) with HubConnection before _hubConnection.start()
Any help?!

CERTIFICATE_VERIFY_FAILED

[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: HandshakeException: Handshake error in client (OS Error: CERTIFICATE_VERIFY_FAILED: ok(handshake.cc:354))

Unable to initialize any of the available transports.

When trying to connect I am getting Unable to initialize any of the available transports. error message. My signalr server is using Microsoft.AspNet.SignalR. I tried connecting to server using javascript signalr library and it worked fine.

Please help.

Is the project abandoned?

Hey, awesome work with this library, but there is this one crucial question that everybody ask themselves when they stumble upon your package. Is it abandoned? There are many issues without an answer or fixes and last version was published on July 11, 2019.

Error when trying to invoke async server method

I connect to the server without problem and I can invoke without problem synchronous methods. But when I try to invoke an asynchronous method I get an error . With the JavaScript client I don't have problem only with the flutter client.There is another problem I found that on the builder when creating the connection there is missing the reconnect property. Despite that great library I appreciate it.

Cannot set headers to connection

AccessTokenFactory only allows to add query parameters, it would be nice to be able to add headers to the hubConnection such as Authorization for Bearer JWT.

invocationId cannot be null

Change

return nonblocking
       ? InvocationMessage(methodName, args, MessageHeaders(), null)
       : InvocationMessage(methodName, args, MessageHeaders(), id.toString());

to return InvocationMessage(methodName, args, MessageHeaders(), id.toString());
or add a check by invocationId and remove (if null) from json before sending

Should I make HubConnection static I have multi screen app

I'm getting disconnected from server and this the error
Unhandled Exception: SocketException: OS Error: No route to host, errno = 113
Should I make the hub connection static to a make the connection stay alive or what to do in this case

Getting connection message as Disconnected and while trying to send message getting exception.

I run your Chat client/server example but at home screen, I am getting the message as disconnected and while I try to send message getting below exceptions.

[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: Cannot start a connection that is not in the 'Disconnected' state.
#0      HubConnection.start (package:signalr_client/hub_connection.dart:103:5)
<asynchronous suspension>
#1      ChatPageViewModel.openChatConnection (package:chatclient/views/pages/chatPageViewModel.dart:63:28)
<asynchronous suspension>
#2      ChatPageViewModel.sendChatMessage (package:chatclient/views/pages/chatPageViewModel.dart:72:11)
<asynchronous suspension>
#3      _MessageComposeViewState.build.<anonymous closure> (package:chatclient/views/pages/chatPage.dart:136:35)
#4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:654:14)
#5      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:729:32)
#6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
#7      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:365:11)
#8      TapGestureRecognizer.handlePrim<…>

My Home screen:

Simulator Screen Shot - iPhone Xʀ - 2019-09-12 at 14 18 19

How to Use

Im new to Flutter frameWork
I want to use signalr on flutter to connect to a server and receive notification
below code is how I do it on Java:

            Platform.loadPlatformComponent(new AndroidPlatformComponent());
            Credentials credentials = new Credentials() {
                @Override
                 public void prepareRequest(Request request) {
                    request.addHeader("username", userId);
                }
            };
            String serverUrl = "http://www.xxxxx.org/";
            mHubConnection = new HubConnection(serverUrl);
            mHubConnection.setCredentials(credentials);
            String SERVER_HUB_CHAT = "notificationHub";
            mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
            ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
            SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);

            try {
                signalRFuture.get();
            } catch (Exception ex) {
                UtilFunctions.showToastMessage(getApplicationContext(), ex);
                return;
            }

            String SERVER_METHOD_SEND = "SendNotifications";
            mHubProxy.invoke(SERVER_METHOD_SEND);

            mHubProxy.on("ReceiveNotification", new SubscriptionHandler1<String>() {
                @Override
                public void run(final String string) {
                   ......
                }
            }, String.class);

But Im not able to implement on flutter
ppreciate any help.
Thanks in advance.

Dose't support asp.net mvc

I have a project with asp.net MVC, not core and i have this error
Response Content-Type not supported: [application/json; charset=UTF-8]

Invalid argument(s): Response Content-Type not supported: [application/json; charset=UTF-8]

Unhandled Exception: Invalid argument(s): Response Content-Type not supported: [application/json; charset=UTF-8]

Any idea how to solve it?

My code:

Future<void> openChatConnection() async {
   if (_hubConnection == null) {
     _hubConnection = HubConnectionBuilder().withUrl(_serverUrl).build();
     _hubConnection.on("RecieveNotification", null);
   }

   if (_hubConnection.state != HubConnectionState.Connected) {
     await _hubConnection.start();
   }
 }

 Future<void> sendChatMessage(String chatMessage) async {
   if( chatMessage == null ||chatMessage.length == 0){
     return;
   }
   await openChatConnection();
   _hubConnection.invoke("SendNotifications");
 }

 void _handleIncommingChatMessage(List<Object> args){
  ......
 }

Support AspNetCore 3.1

I've made an attempt at aligning the code to the AspNetCore 3.1 Typescript client in order to support auto-reconnect. I've upgraded the chat and test apps (+servers) and both appear to be fine.

I'd be grateful if anybody could give my dev branch a test in your own use cases to see if there are any issues.

@soernt The branch has a few significant changes so would be a large PR but if you are interested let me know. Thanks for doing most of the work on this too by the way.

VM chatmessages disapper when disconnected

Hi,
I found that sometimes it will turn disconnected when in simulator. At the same time , the chatmessages in listbuilder disappeared. It will shown up after connect.

How could retain the message even disconnect?

Cheers,

Error when using with token

I am receiving error:

[VERBOSE-2:ui_dart_state.cc(166)] Unhandled Exception: 302: Found

when using token with asp.net core hub

  HttpConnectionOptions httpConnectionOptions = new HttpConnectionOptions(accessTokenFactory: () async => await getAccessToken());
  _hubConnection = HubConnectionBuilder().withUrl(_serverUrl, options: httpConnectionOptions).build();

not fixing it

Flutter SignalR method not being invoked correctly

This is my CommentHub in flutter:

// Import the library.
import 'package:signalr_client/signalr_client.dart';
import 'package:logging/logging.dart';
import 'package:xperience/models/global.dart';
// The location of the SignalR Server.
final serverUrl = "http://" + base + ":8070/CommentHub";

final hubConnection = HubConnectionBuilder().withUrl(serverUrl).build();

class HubService {
  static final hubProtLogger = Logger("SignalR - hub");
  static final  transportProtLogger = Logger("SignalR - transport");
  static final connectionOptions = HttpConnectionOptions;

  static final httpOptions = new HttpConnectionOptions(logger: transportProtLogger);
  HubConnection hubConnection = HubConnectionBuilder().withUrl(serverUrl, options: httpOptions).configureLogging(hubProtLogger).build();
  bool connectionIsOpen;

  Future<void> openChatConnection() async {
    if (hubConnection == null) {
      hubConnection.onclose((error) => connectionIsOpen = false);
    }

      await hubConnection.start();
      connectionIsOpen = true;

  }
  @override
  Future<void> executeTest(String json) async {

    hubConnection.on("AddUser", _handleServerInvokeMethodSimpleParametersNoReturnValue);
    try {
      await hubConnection.invoke("AddUser",args:<Object>[json]);
    } finally {
      hubConnection.off("AddUser", method: _handleServerInvokeMethodSimpleParametersNoReturnValue);
    }
  }

  void _handleServerInvokeMethodSimpleParametersNoReturnValue(List<Object> parameters) {

    final paramValues = new StringBuffer("Parameters: ");
    for(int i = 0; i < parameters.length; i++){
      final value = parameters[i];
      paramValues.write( "$i => $value, ");
    }

    print("From Callback: Server invoked method 'ServerInvokeMethodSimpleParametersNoReturnValue': " + paramValues.toString());
  }

  Future removeUser() async {
//    final result = await hubConnection.invoke("RemoveUser",args: <Object>[]);
//    print(result);
    hubConnection.stop();
    //hubConnection.onclose( (error) => print("Connection Closed"));

  }
}

This is my CommentHub.cs in asp.net core:

using System;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using Xperience.Data.Entities.Posts;

namespace Xperience.Hub
{
    public class CommentHub : Microsoft.AspNetCore.SignalR.Hub
    {
        public static List<Connection> Connections = new List<Connection>();

        public void AddUser(string json) {
      
string []arr=json.split(",");
            Connections.Add(new Connection
            {
                ConnectionId = Context.ConnectionId,
                UserId = json[0],
                PostId = json[1]
            });
        }
        public void RemoveUser() {
            var user = Connections.Find(x => x.ConnectionId == Context.ConnectionId);
            Connections.Remove(user);
        }

    }

    public class Connection { 
        public string ConnectionId { get; set; }
        public string UserId { get; set; }
        public int PostId { get; set; }
    }
}

Can someone please tell me what's the wrong thing im doing as im always getting this error when i invoke executeTest:

Unhandled Exception: type 'GeneralError' is not a subtype of type 'Error' in type cast

How to pass complex object as parameter

The following code throws Converting object to an encodable object failed: Instance of 'InvocationMessage'

_hubConnection.invoke("Broadcast", args: [request, broadMessage]);

I already implemented toJson() as per instruction
use objects that implements toJson() since that method is used by the dart:convert package to serialize an object. here https://pub.dartlang.org/packages/signalr_client

class NotificationRequest {
  int connectionType;
  String command;
  int userId;
  String userName;
  String uuid;

  NotificationRequest(
      {this.command,
      this.connectionType,
      this.userId,
      this.userName,
      this.uuid});

  Map<String, dynamic> toJson() => {
        'connectionType': connectionType,
        'command': command,
        'userId': userId,
        'userName': userName,
        'uuid': uuid
      };
}
class BroadCastMessage {
  String message;
  BroadCastMessage({this.message});
  Map<String, dynamic> toJson() => {'message': message};
}

Having trouble with Starting connection on shared host

Hello Sörnt,

After getting things working fine on my local IIS, I have migrated (web-deploy) my web-api site to a shared host (SmarterASP.net). Everything in the web-api site works fine, except SignalR. Using the same Flutter client, when I try to 'start' the connection, I get errors back. Here is the output:

flutter: FINER: 2019-04-16 20:01:37.074299: Starting HubConnection.
flutter: FINER: 2019-04-16 20:01:37.074538: Starting connection with transfer format 'TransferFormat.Text'.
flutter: FINER: 2019-04-16 20:01:37.074753: Sending negotiation request: http://core.totalinsulators.com/activity/negotiate
flutter: FINEST: 2019-04-16 20:01:37.108143: HTTP send: url 'http://core.totalinsulators.com/activity/negotiate', method: 'POST' content: ''
flutter: FINER: 2019-04-16 20:01:37.317341: Selecting transport 'HttpTransportType.WebSockets'
flutter: FINEST: 2019-04-16 20:01:37.317636: (WebSockets transport) Connecting
flutter: FINEST: 2019-04-16 20:01:37.317825: WebSocket try connecting to 'ws://core.totalinsulators.com/activity?id=pqZn4dku_8kKw9ZPf1hQ9A'.
flutter: SEVERE: 2019-04-16 20:01:37.594430: Failed to start the transport 'HttpTransportType.WebSockets': WebSocketException: Connection to 'http://core.totalinsulators.com:0/activity?id=pqZn4dku_8kKw9ZPf1hQ9A#' was not upgraded to websocket
flutter: FINER: 2019-04-16 20:01:37.594694: Selecting transport 'HttpTransportType.ServerSentEvents'
flutter: FINER: 2019-04-16 20:01:37.594864: Sending negotiation request: http://core.totalinsulators.com/activity/negotiate
flutter: FINEST: 2019-04-16 20:01:37.608133: HTTP send: url 'http://core.totalinsulators.com/activity/negotiate', method: 'POST' content: ''
flutter: FINEST: 2019-04-16 20:01:37.734439: (SSE transport) Connecting
flutter: FINER: 2019-04-16 20:01:37.734978: Sending handshake request.
flutter: FINEST: 2019-04-16 20:01:37.735238: Sending message.
flutter: FINEST: 2019-04-16 20:01:37.735467: (SSE transport) sending data.
flutter: FINEST: 2019-04-16 20:01:37.735974: HTTP send: url 'http://core.totalinsulators.com/activity?id=svK4GauaoO4qHqINyMOpSw', method: 'POST' content: '{"protocol":"json","version":1}<…>
flutter: had error starting hub connection: HttpException: Invalid response status code, uri = http://core.totalinsulators.com/activity?id=svK4GauaoO4qHqINyMOpSw

I am guessing this might be a server thing, but would like your opinion before asking the Server people. If it helps, when I did my 'publish', my options were:

Configuration: Release 
Target Framework: netcoreapp2.2
Deployment Mode: Self-Contained
Target Runtime: win-x86

Those were based on recommendations by the host vendor.

Thank you.

Cannot get client and/or server to work

I have a Flutter app that I would like to receive real-time broadcasts from my IIS .netcore web-api server. I initially had my web-api written in .net framework, but have now re-written it for .net core 2.2. As far as I can 'see' everything is setup properly, however there are two 'problems':

  1. On my server, my 'hub' class never seems to have any clients, i.e., the following statement never happens:
    Clients.All.SendCoreAsync("clientFunctionName", new object[] { name, message });
    The reason this never happens is that I have an If (Clients != null) test before it, and, Clients is always null. I have tried injecting IHubContext into my Hub class, but that has not helped. I am 'assuming' that Clients would in fact be null IF no clients had ever started() a signalR connection? Keep in mind that for my 'test' code I am doing an entire 'cycle' within the same Flutter class/screen. In other words, when I 'load' a Flutter screen, I open (start) the connection to my signalR hub. Then later on that same screen issues a web-api call to fetch some data. Within the .net core code then, before the web-api method 'returns' any data, but after the connection was started by the client, I make the hub method call to broadcast to all connected clients. But again, Clients is always null, so nothing is broadcast.

  2. As explained in a response to a different issue here, I intermittently receive the 'cannot await a future on a null _handshakeCompleter. Maybe the solution to that will 'fix' my first issue. Maybe even when I DO get a successful connection, I really am not connected? How else are the Clients always null, even after a successful connection/start?

I also have some general questions. I want to get things 'right' within my Flutter code. My screens (routes/classes) are 'basic vanilla Flutter - no MVC. Other than ScopedModel for some 'global' stuff, I use setState() and most presentation code exists in the same class as the event handling code. Currently I am 'declaring' the _hubConnection object var within my Flutter screen's (class's) declaration block. I then instantiate ( _hubConnection = HubConnectionBuilder().withUrl(_serverUrl).build() ) within the didChangeDependencies() method, which I have made async. Should I be doing it here? Versus ?? initState ?? I've tried it there and it did not seem to matter, but wanted to ask. Also, I am performing the instantiation within a setState((){}) block, so that _hubConnection is updated within overall state. Is that correct? Then again, the actual .start() call, which is an 'await' cannot be performed within a setState() block, so, ... is that ok?

I realize that this plug-in is not responsible for my server code. That said, I am hoping that you, or some other users doing similar things, might be able to shed some light on my situation. I will gladly provide more code if necessary.

Thank you!

It is not possible to use hubConnection.start().then(onValue, onError)

When i try to use hubConnection.start().then() and i let it connect to a non-existent server (causes an error offcourse) the application crashes with the following error:

Unhandled Exception: type 'GeneralError' is not a subtype of type 'Error' in type cast

This happends in the file hub_connection.dart on line 244.

completer.completeError(error as Error);

This line tries to cast the error to the type 'Error'. As a lot of the errors in this library are of type 'GeneralError', that fails.
As far as i know there is no reason that it casts to 'Error' as the same function is called with the type 'GeneralError' just a few lines above it.

completer.completeError(new GeneralError(
"Unexpected message type: ${invocationEvent.type}"));
}

A fix for this would be to remove the cast in line 244 of hub_connection.dart. Like this:

completer.completeError(error);

SocketException: Reading from a closed socket

Hi, I have encountered this problem. I am wondering how to fix it.

Unhandled Exception: SocketException: Reading from a closed socket
#0 _RawSecureSocket.read (dart:io/secure_socket.dart:699:7)
#1 _Socket._onData (dart:io-patch/socket_patch.dart:1830:27)
#2 _rootRunUnary (dart:async/zone.dart:1134:38)
#3 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
#4 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
#5 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
#6 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:265:7)
#7 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:766:19)
#8 _StreamController._add (dart:async/stream_controller.dart:642:7)
#9 _StreamController.add (dart:async/stream_controller.dart:588:5)
#10 _RawSecureSocket._sendReadEvent (dart:io/secure_socket.dart:1018:19)
#11 _rootRun (dart:async/zone.dart:1122:38)
#12 _CustomZone.run (dart:async/zone.dart:1023:19)
#13 _CustomZone.runGuar<…>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.