soernt / signalr_client Goto Github PK
View Code? Open in Web Editor NEWA Flutter SignalR Client for ASP.NET Core
License: MIT License
A Flutter SignalR Client for ASP.NET Core
License: MIT License
How to cancel a timeout connection,Is there a way to set the CancellationToken?
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){
......
}
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)
Some times get error in hubconnection.start() method with a message future was called on null .The error is exactly on _handshakeCompleter.future .How can resolve it ??
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
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.
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
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]
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,
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<…>
When server is offline status , hubConnection.start() method need very long time for wait . about 90+ seconds, Can I set timeout param for a connect ?
Is it possible to use Azure SignalR with this component or do you have plans to implement this?
I need to pass Parameter(Not a token but sth like an Id) with HubConnection before _hubConnection.start()
Any help?!
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
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':
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.
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!
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};
}
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.
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
I Recently encountered this issue,
Unhandled Exception: type 'GeneralError' is not a subtype of type 'Error' in type cast
package:signalr_client/hub_connection.dart:244
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:
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.
had to add quiver to my pubspec.yaml
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
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.
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
You cannot connect a .Net application to this package with.
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.
signalr_client/lib/hub_connection.dart
Line 244 in 288cb37
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.
signalr_client/lib/hub_connection.dart
Lines 236 to 238 in 288cb37
A fix for this would be to remove the cast in line 244 of hub_connection.dart. Like this:
completer.completeError(error);
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.
Can I use this pub in background task?
Because when I close my App, I lose my connection with the server.
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: HandshakeException: Handshake error in client (OS Error: CERTIFICATE_VERIFY_FAILED: ok(handshake.cc:354))
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.
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.
I need send data to server either headers or query string ....
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.
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.