android signalr jar,SignalR在Android上的实践

闲言

因为我们后台是 .net,所以要求使用SignalR来实现推送。因为网上资料也不多,也走了很多弯路。现在记录一下,希望可以帮到更多的人。

首先要确认后台用的是 asp.net 还是 asp.net core ,这两个的SignalR还是有区别的,我们Android用的库也不一样,我认为是不兼容的。

如果使用的是 asp.net,这里有个库可以使用。java-client 但是不再维护了。也可以试试这个,但是也不维护了。

如果后台使用的是 asp.net core ,那就接着看吧。

实践

这里我们说的后台是 asp.net core,我们该怎么办。首先看一下官网的一些信息。 另外,还有github上的地址

官网上给出了使用的步骤:

添加依赖

implementation 'com.microsoft.signalr:signalr:1.0.0'

//下面这个是日志输出,上面这个库用到了这个

implementation group: 'org.slf4j', name: 'slf4j-android', version: '1.7.7'

代码

HubConnection hubConnection;

public void signalr() {

//创建HubConnection

hubConnection = HubConnectionBuilder.create(url)

.build();

//客户端需要在hubConnection对象执行start()方法之前对服务端需要调用的方法进行注册

//这里的message是服务端发给我们的信息

hubConnection.on("SendAsync", (message) -> {

Logger.d("gxh",message+"#haha");

}, String.class);

new HubConnectionTask().execute(hubConnection);

}

class HubConnectionTask extends AsyncTask {

@Override

protected void onPreExecute() {

super.onPreExecute();

}

@Override

protected Void doInBackground(HubConnection... hubConnections) {

HubConnection hubConnection = hubConnections[0];

//开始连接并等待连接成功

hubConnection.start().blockingAwait();

Logger.d("gxh",hubConnection.getConnectionState().toString());

return null;

}

}

//客户端调用服务端的方法 ,这里的方法名和参数要参考服务端写的,要一致。

hubConnection.send("Send", "hhhhhhhhh");

按照上面的步骤,你看下日志,如果连接成功了,那ok了。不用接着看了。

但是我还是失败了(可以连接到该库的测试地址上,但是连不上我们服务器的地址上)。

04-18 14:09:14.827 3655-3724/cn.gxh.view E/OkHttpWebSocketWrapper: WebSocket closed from an error: Expected 'Connection' header value 'Upgrade' but was 'null'.

04-18 14:09:14.828 3655-3724/cn.gxh.view I/WebSocketTransport: WebSocket connection stopping with code null and reason 'Expected 'Connection' header value 'Upgrade' but was 'null''.

04-18 14:09:14.828 3655-3724/cn.gxh.view E/c*.m*.s*.HubConnection: HubConnection disconnected with an error Expected 'Connection' header value 'Upgrade' but was 'null'.

--------- beginning of crash

04-18 14:09:14.831 3655-3724/cn.gxh.view E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher

Process: cn.gxh.view, PID: 3655

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.microsoft.signalr.HubConnection$ConnectionState.cancelOutstandingInvocations(java.lang.Exception)' on a null object reference

at com.microsoft.signalr.HubConnection.stopConnection(HubConnection.java:431)

at com.microsoft.signalr.HubConnection.lambda$start$6$HubConnection(HubConnection.java:301)

at com.microsoft.signalr.HubConnection$$Lambda$19.invoke(Unknown Source)

at com.microsoft.signalr.WebSocketTransport.onClose(WebSocketTransport.java:93)

at com.microsoft.signalr.WebSocketTransport.lambda$start$1$WebSocketTransport(WebSocketTransport.java:56)

at com.microsoft.signalr.WebSocketTransport$$Lambda$1.invoke(Unknown Source)

at com.microsoft.signalr.OkHttpWebSocketWrapper$SignalRWebSocketListener.onFailure(OkHttpWebSocketWrapper.java:98)

at okhttp3.internal.ws.RealWebSocket.failWebSocket(RealWebSocket.java:570)

at okhttp3.internal.ws.RealWebSocket$2.onResponse(RealWebSocket.java:197)

at okhttp3.RealCall$AsyncCall.execute(RealCall.java:153)

at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)

at java.lang.Thread.run(Thread.java:761)

按照该库维护人员的建议:upgrade to the 3.0.0-preview3-19153-02 version.

implementation 'com.microsoft.signalr:signalr:3.0.0-preview3-19153-02'

因为这个版本 can set the transport to LongPolling

hubConnection = HubConnectionBuilder.create(url)

.withTransport(TransportEnum.LONG_POLLING)

.build();

其它无变化,至此,连接成功。

04-19 11:15:53.986 7924-7954/cn.gxh.view I/c*.m*.s*.HubConnection: HubConnection started.

04-19 11:15:53.988 7924-7951/cn.gxh.view E/gxh: CONNECTED

04-19 11:15:54.048 7924-7960/cn.gxh.view E/gxh: User tom: hi Baby#haha

最后,还有一点要说的,按照官网上写的:

The Java client is available in ASP.NET Core 2.2 and later.

这个库是在 asp.net core 2.2以及以后才可以用的,但是吧,该库的维护人员说2.1应该也可以用。所以,尽管试试吧。

文章同步发布在博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; namespace SignalR.通讯 { public class iHub : iHubBase { public override Task OnConnected() { // 查询用户 var user = 自我意识.你们.SingleOrDefault(u => u.ContextId == Context.ConnectionId); if (user != null) return base.OnConnected(); user = new 线程(Context.ConnectionId); user.目的 += User_目的事件; 自我意识.你们.Add(user); Clients.Client(Context.ConnectionId).addMessage("请输入用户姓名 ", Context.ConnectionId); return base.OnConnected(); } private void User_目的事件(object sender, 目的事件参数 e) { var user = (线程)sender; if (e.类型 == 目的事件类型.说话) { if (user != null) { Clients.Client(user.ContextId).addMessage("电脑说:" + e.参一+ e.参二, user.ContextId); } } else if (e.类型 == 目的事件类型.学习 || e.类型 == 目的事件类型.认知) { Clients.Client(user.ContextId).doclass(e.参一, e.参二); } else if (e.类型 == 目的事件类型.意识) { Clients.Client(user.ContextId).addIdea(e.参一, e.参二); } } /// <summary> /// 获取用户名和自己的唯一编码 /// </summary> public void GetName(string 姓名) { // 查询用户。 var user = 自我意识.你们.SingleOrDefault(u => u.ContextId == Context.ConnectionId); if (user != null) { user.姓名 = 姓名; Clients.Client(Context.ConnectionId).showNameAndId(user.姓名, Context.ConnectionId); //读取用户个性数据 } GetOnlineUserList(); } public override Task OnReconnected() { // 查询用户 var user = 自我意识.你们.SingleOrDefault(u => u.ContextId == Context.ConnectionId); if (user != null) return base.OnReconnected(); user = new 线程(Context.ConnectionId); user.目的 += User_目的事件; 自我意识.你们.Add(user); //自动重新登陆 Clients.Client(Context.ConnectionId).addMessage("重新连接。。。 ", Context.ConnectionId); GetOnlineUserList(); return base.OnReconnected(); } /// <summary> /// 重写断开连接事件 /// 用户断开连接后,需要移除在线人们 /// </summary> /// <param name="stopCalled"></param> /// <returns></returns> public override Task OnDisconnected(bool stopCalled) { var user = 自我意识.你们.FirstOrDefault(u => u.ContextId == Context.ConnectionId); //判断用户是否存在,存在则删除 if (user != null) { 自我意识.你们.Remove(user); } //更新所有用户的列表 GetOnlineUserList(); return base.OnDisconnected(stopCalled); } /// <summary> /// 获取所有在线用户 /// </summary> public void GetOnlineUserList() { // var item = from a in 自我意识.人们 select new { a.印象.姓名, a.ContextId }; //var jsondata = JsonConvert.SerializeObject(item.ToList()); // Clients.All.getOnlineUserlist(jsondata);// 调用客户端的getOnlineUserlist来获得在线人们 } /// <summary> /// 发送消息 /// </summary> /// <param name="contextId">发送给用户的ContextId</param> /// <param name="message">发送的消息内容</param> public void SendMessage(string contextId, string message) { 线程 你 = 自我意识.你们.FirstOrDefault(u => u.ContextId == Context.ConnectionId); /* // 判断用户是否存在,存在则发送 if (user != null) { // 1V1 聊天,需要把消息往这2个客户端发送 // 给指定用户发送,把自己的ID传过去 // Clients.Client(contextId).addMessage(message + " " + DateTime.Now, Context.ConnectionId); // 给自己发送,把用户的ID传给自己 Clients.Client(Context.ConnectionId).addMessage(message + " " + DateTime.Now, contextId); } else { // Clients.Client(Context.ConnectionId).showMessage("该用户已离线"); } */ if (你 == null) { //重新连接 } if (你.姓名.Equals(string.Empty)) { GetName(message); Clients.Client(Context.ConnectionId).addMessage("用户" + 你.姓名 + "你好", contextId); } else { Clients.Client(Context.ConnectionId).addMessage(你.姓名 + ":" + message + " " + DateTime.Now, contextId); //开始正式聊天 你.输入(message); } } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值