Android 关于SignalR的使用

前言

      最近开发项目。后台是用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();

至此结束。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值