我是Flutter frameWork的新手
我想在 flutter 上使用 signalr 连接到服务器并接收通知
下面的代码是我在 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);
但是我无法实现感谢任何帮助。
提前致谢。
最佳答案
添加signalr_client 0.1.6
导入import 'package:signalr_client/signalr_client.dart';
创建这样的方法:
void StartSocket() async {
final serverUrl = "server_url";
final httpOptions = new HttpConnectionOptions(accessTokenFactory: GetToken); //optional
hubConnection = HubConnectionBuilder().withUrl(serverUrl, options: httpOptions).build();
hubConnection.serverTimeoutInMilliseconds = 10 * 60 * 60 * 1000;
hubConnection.keepAliveIntervalInMilliseconds = 10 * 60 * 60 * 1000;
await hubConnection.start();
hubConnection.onclose((error) {
print("Connection Closed");
StartSocket();
});
}
用于调用服务器功能:hubConnection.invoke("server_function_name");
用于定义服务器可以调用的函数:hubConnection.on("client_function_name", (List<Object> parameters) {
});