前言
最近开发项目。后台是用C#开发,Android 移动端与后台之间的通信就可以使用signalR。其实使用方法也是挺简单的。
正文
步骤一:
在build.gradle中引入依赖。接着进行Sync同步。即可开始使用了。
implementation 'com.microsoft.signalr:signalr:3.1.2'
步骤二:
创建HubConnection对象。
hubConnection = HubConnectionBuilder.create(UUIDManager.SERVICE_URL+"rtcmsg")
.withAccessTokenProvider(Single.defer(() -> {
// Your logic here.
String token = "android";
return Single.just(token);
})).build();
hubConnection.setServerTimeout(4 * 60 * 1000);//超时
hubConnection.setKeepAliveInterval(2 * 60 * 1000);//心跳
注意:create()里面设置的地址写你服务端的地址。withAccessTokenProvider里面的return值跟后台确认再填上。博主这里是一个简单的字符串token。
步骤三:
接收消息方法设置。
hubConnection.on("SDKSig", (type, json) -> {
Log.e("jochen", "hubConnection SDKSig:New type: " + type + ",json: " + json);
}, Integer.class, String.class);
注意:这里的方法名和参数必须与后台方法名保持一致。包括数据类型。
步骤四:
进行连接。这里是为了防止抛异常就加了try-catch。其实不加也没问题。根据自身情况来决定。
try {
hubConnection.start().blockingAwait(); //进行连接
} catch (Exception e) {
e.printStackTrace();
Log.e("jochen", "hubConnection link fail 1," + e.getMessage());
}
连接成功后,在步骤三中的方法里面就可以接收到服务端发过来的数据了。
到此为止,一个简单的SignalR通信就完成了。下面是一些状态监听的方法回调和数据发送。
步骤五:
连接状态监听。
hubConnection.onClosed(exception -> Log.i("jochen", "Closed: hubConnection"));
步骤六:
数据发送。
hubConnection.invoke("Login", "android", SnStr, token);
数据发送也比较简单,一句话搞定。我们看一下invoke()方法定义。
public Completable invoke(String method, Object... args) {
hubConnectionStateLock.lock();
try {
if (hubConnectionState != HubConnectionState.CONNECTED) {
throw new RuntimeException("The 'invoke' method cannot be called if the connection is not active.");
}
String id = connectionState.getNextInvocationId();
CompletableSubject subject = CompletableSubject.create();
InvocationRequest irq = new InvocationRequest(null, id);
connectionState.addInvocation(irq);
Subject<Object> pendingCall = irq.getPendingCall();
pendingCall.subscribe(result -> subject.onComplete(),
error -> subject.onError(error),
() -> subject.onComplete());
// Make sure the actual send is after setting up the callbacks otherwise there is a race
// where the map doesn't have the callbacks yet when the response is returned
sendInvocationMessage(method, args, id, false);
return subject;
} finally {
hubConnectionStateLock.unlock();
}
}
可以看到。第一个参数是方法名。跟后台方法名对应一致。后面就是跟的参数,也是跟后台方法保持一致。
步骤七:
关闭连接。
hubConnection.stop();
至此结束。