ASP.NET Core SignalR용 Flutter 클라이언트로, Flutter 앱과 .NET Core 백엔드 간의 실시간 통신을 가능하게 합니다. 서버 측 허브 메서드를 호출하고 서버에서 온 메서드 호출을 수신할 수 있어, 실시간 업데이트, 채팅 애플리케이션 및 협업 도구에 적합합니다. Android, iOS, macOS, Windows, Linux에서 작동하여 광범위한 플랫폼 호환성을 보장합니다. SignalR 프로토콜 기반으로 구축되어 효율적이고 낮은 지연 시간의 메시징을 제공하며, 자동 재연결 및 백업 메커니즘을 갖추고 있습니다.
사용 사례
실시간 채팅 애플리케이션
실시간 데이터 대시보드
협업 편집 도구
사물인터넷 장치 모니터링
푸시 알림
주요 기능
양방향 통신
자동 재연결
크로스 플랫폼 지원
서버 메서드 호출
클라이언트 이벤트 처리
적합한 대상
실시간 앱 개발자
백엔드 통합형 플러터 프로젝트
실시간 업데이트가 필요한 응용 프로그램
ASP.NET Core SignalR를 사용하는 팀
저지연 통신 요구 사항
고려 사항
호환되는 ASP.NET Core SignalR 서버가 필요합니다
네트워크 안정성은 성능에 영향을 미칩니다
보안 허브를 위한 인증 설정이 필요합니다
네이티브 라이브러리에 비해 문서가 제한적
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
signalr_client
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.
Tested with ASP.NET Core 3.1 & ASP .NET Core 6
The client is able to invoke server side hub functions (including streaming functions) and to receive method invocations issued by the server. It also supports the auto-reconnect feature.
The client supports the following transport protocols:
Important Note: if you are experiencing issues (for example not receiving message callback) with the latest version, please give a try to older version as signalr_netcore: 0.1.7+2-nullsafety.3 but bear in mind that this version does not support auto reconnect functionalities and need to be handled manually.
Usage
Let's demo some basic usages:
1. Create a hub connection:
// Import the library.import'package:signalr_netcore/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"));
// Import theses libraries.import'package:logging/logging.dart';
import'package:signalr_netcore/signalr_client.dart';
// Configer the loggingLogger.root.level = Level.ALL;
// Writes the log messages to the consoleLogger.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 = HttpConnectionOptionsfinal httpOptions = newHttpConnectionOptions(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
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":
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");
}
5. Using Msgpack for serialization
The Hub should be configured to use the msgpack protocol in both the client and server
Client
import'package:signalr_netcore/msgpack_hub_protocol.dart';
_hubConnection = HubConnectionBuilder()
.withUrl(_serverUrl, options: httpOptions)
/* Configure the Hub with msgpack protocol */
.withHubProtocol(MessagePackHubProtocol())
.withAutomaticReconnect()
.configureLogging(logger)
.build();
Server
Add the following packge to your ASP NET core project
Microsoft.AspNetCore.SignalR.Protocols.MessagePack
public void ConfigureServices(IServiceCollection services)
{
// Configure the hub to use msgpack protocol
services.AddSignalR().AddMessagePackProtocol();
}
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.