第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > Android Signal 使用

Android Signal 使用

时间:2019-12-14 17:24:21

相关推荐

Android Signal 使用

一、官方

文档地址

示例代码

二、使用前说明

一定要注意使用的Signal的版本号,如果客户端与服务端的版本不一致,可能会出现收不到消息的问题!!!

三、使用

添加依赖

//signalrimplementation 'com.microsoft.signalr:signalr:7.0.0'//也可以加入日志,文档中有写//implementation 'org.slf4j:slf4j-jdk14:1.7.25'

编译没问题,但是运行的时候会报错

//在Android标签下添加这个,因为signalr中包含okhttp3引起的冲突configurations {all*.exclude group: 'com.squareup.okhttp3', module: 'okhttp'}

解决办法

当然也有说引入library依赖的方法

解决办法1

githup

创建连接

关键类com.microsoft.signalr.HubConnection和com.microsoft.signalr.HubConnectionBuilder

HttpHubConnectionBuilder httpHubConnectionBuilder = HubConnectionBuilder.create(serverUrl你的地址);//可以设置其他的参数 HubConnection hubConnection = httpHubConnectionBuilder.withTransport(TransportEnum.WEBSOCKETS).build();//hubConnection = httpHubConnectionBuilder.build();

接收消息

//与服务器交互,接收服务器的消息//ReceiveMsg 与服务器约定的方法//String.class 接收的类型,与服务器约定//务必放在连接之前,hubConnection.start().blockingAwait()方法之前,不然无效hubConnection.on("ReceiveXXMessage", new Action1<String>() {@Overridepublic void invoke(String message) {//子线程//UI操作请切换到主线程,不然会出现不显示等问题}}, String.class);

设置关闭连接的监听

//对被动关闭进行监听(比如网络异常)hubConnection.onClosed(new OnClosedCallback() {@Overridepublic void invoke(Exception exception) {Log.i("zxd", "exception: " + exception.getMessage());}});

开始连接

hubConnection.start().blockingAwait();

关闭连接

hubConnection.stop()

发送消息

/**与服务器交互,给服务器发消息SendMsg 与服务器约定的方法str1 与服务器约定的字段*/hubConnection.send("SendMsg", str1);//hubConnection.send("SendMsg", str1, str2);//参数个数为不固定

连接的状态

if (hubConnection.getConnectionState() == HubConnectionState.DISCONNECTED) {hubConnection.start().blockingAwait();}

三种状态:

CONNECTED,//已连接DISCONNECTED,//未连接CONNECTING,//连接中

参考

SignalR ——Android实践 kt

SignalR ——Android实践

Android 通过SignalR与服务器交互

Android signalr

android封装signalR的demo

.NET CORE SignalR Android 客户端

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。