开发者社区> 操张林> 正文

Xamarin android中使用signalr实现即时通讯

简介: 前面几天也写了一些signalr的例子,不过都是在Web端,今天我就来实践一下如何在xamarin android中使用signalr,刚好工作中也用到了这个,也算是总结一下学到的东西吧,希望能帮助你们,更快地熟悉使用xamarin android进行即时通讯。
+关注继续查看

前面几天也写了一些signalr的例子,不过都是在Web端,今天我就来实践一下如何在xamarin android中使用signalr,刚好工作中也用到了这个,也算是总结一下学到的东西吧,希望能帮助你们,更快地熟悉使用xamarin android进行即时通讯。

先来看一下最终实现的效果:


这个简单的例子主要分为两部分:

1.一个Signalr web端提供访问的地址,也就是前面所写的例子 MVC中使用signalR入门教程。发布这个web网页,为Xamarin android的signalr客户端 提供一个url地址连接

2. xamarin android 中引入signalr.client 库,通过连接web地址发送消息,接收消息。

1.发布web网站提供地址

这个web网站我就不再演示了,发布用的还是 MVC中使用signalR入门教程这个例子,集线器类ServerHub 有一个服务器端的方法SendMsg(发送消息)和一个客户端调用的方法showMessage(接收消息)。我稍作了一下修改,会显示是哪个发送消息的设备名称。发布成功后添加的是的路由器的地址,如图:

2.新建xamarin android项目引入Signalr.Client 库

引入signalr.client 库非常郁闷,我昨天直接从nuget上引入signalr.client 库的时候,运行项目总是报这个错误,耽误好长时间。估计你们引入的时候也会出现这个错误:


Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'System.Net.Http.Extensions, Version=1.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Perhaps it doesn't exist in the Mono for Android profile?
文件名:“System.Net.Http.Extensions.dll”
   在 Xamarin.Android.Tuner.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)

   在 Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences(ICollection`1 assemblies, AssemblyDefinition assembly, Boolean topLevel)
   在 Xamarin.Android.Tasks.ResolveAssemblies.Execute()

这个错误说明signalr.client 在xamarin android支持的还不够好,今天厂里的牛哥说是nuget上面引入库不兼容,所以只能在xamarin官网上下载后引入。如果你们也是这样的错误,可以下载这个示例xamarin signalr入门例子,引入里面的signalr.client 库。开发xamarin android项目的时候总会碰到很多小错误,虽然不是什么大bug,但是目前圈子很小,百度能解决的不是很多,有基础的话逛逛StackOverflow 还是不错的选择。有些小错误,能真是能让你喝一壶的.....,

引入好signalr.client 之后,新建一个类SignalrChatClient这是这个即时通讯的桥梁,as shown in the figure


3.SignalrChatClient负责创建、发送消息、接受消息的方法

SignalrChatClient.cs,代码如下

using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Client;
namespace SignalrClientDemo
{
    public  class SignalrChatClient
    {
        private readonly HubConnection _connection;
        private readonly IHubProxy _proxy;//客户端代理服务器端中心
        public event EventHandler<string> OnReceiveEvent; //定义一个接收server端的事件
        public SignalrChatClient()
        {
            _connection = new HubConnection($"http://192.168.16.137:400");
            _proxy = _connection.CreateHubProxy("serverHub");
        }
        //负责连接的方法
        public async Task  Connect()
        {
           await  _connection.Start();
            _proxy.On("showMessage", (string  platform,string msg) =>
            {
                    OnReceiveEvent(this,platform+":" +msg);
            });
        }
        public  Task Send(string message)
        {
            string serverMethod = "sendMsg"; //serverHub中定义的server端方法名称
            if (_connection.State != ConnectionState.Connected)
            {
                Console.WriteLine("未连接");
                return null;
            }
            Console.WriteLine("已连接");
           return   _proxy.Invoke(serverMethod,message);//Invode the 'SendMessage' method on ther server 
        }
    }
}

4.最后一步Activity的布局和使用SignalrChatClient

Main.axml布局比较简单,Adapter使用的是ArrayAdapter
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/et_msg"
        android:layout_width="match_parent"
        android:textColor="#ff0000"
        android:layout_height="50dp" />
    <Button
        android:id="@+id/MyButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/Hello" />
    <ListView
        android:id="@+id/lv_msg"
        android:layout_width="match_parent"
        android:layout_height="30dp" />
</LinearLayout>

MainActivity.cs

using Android.App;
using Android.Widget;
using Android.OS;
namespace SignalrClientDemo
{
    [Activity(Label = "SignalrClientDemo", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        int count = 1;
        protected override async void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            Button button = FindViewById<Button>(Resource.Id.MyButton);
            EditText et_msg = FindViewById<EditText>(Resource.Id.et_msg);
            ListView lv_msg = FindViewById<ListView>(Resource.Id.lv_msg);
            SignalrChatClient client = new SignalrChatClient();
            await client.Connect();
            var adapter = new ArrayAdapter(this,Android.Resource.Layout.SimpleListItem1);
            string msg = et_msg.Text;
            //发送消息
            button.Click += delegate {
                client.Send(msg);
                et_msg.Text = string.Empty;
            };
            lv_msg.Adapter = adapter;
            //使用委托接收消息
            client.OnReceiveEvent += (sender, message) => RunOnUiThread(() =>
            {
                adapter.Add(message);
            });
        }
    }
}
实现了这个效果聊天的效果之后,会发现这xamarin android客户端使用signalr实现即时通讯的方式和mvc里的差不多,方式其实是一样的,客户端发送的消息的事件也是要调用服务器端的serverHub类中方法sendMsg,接收消息同样是在委托里定义服务器端中声明的客户端方法showMessage.原理很相似。最近工作之余不是很忙,准备写一个聊天的xamarin android项目出来,希望能快点做出来吧。

例子下载地址:xamarin signalr入门例子

作者:张林

标题:Xamarin android中使用signalr实现即时通讯 原文地址:http://blog.csdn.net/kebi007/article/details/53544379

转载随意注明出处




版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
Android即时通讯设计——腾讯IM接入和WebSocket接入
之前项目的群聊是用数据库直接操作的,体验很差,消息很难即时反馈,所以最后考虑到了使用腾讯的IM完成群聊的接入,不过中途还是有点小坎坷的,接入完成之后发现体验版一个群聊只有20人,当时看到体验版支持100个用户也就忍了,现在一个群聊只能20用户,忍不了了,所以暂时找到了**WebSocket**作为临时的解决方案(等有钱了再换),同时支持50个用户在线聊天,也算还行,勉强够用,下面就介绍两种实现方案的接入,正文即将开始~~
251 0
.NET(WinCE、WM)开发转Android开发 ——Xamarin和Smobiler对比
WinCE从1995年诞生至今,已有20多年的发展历史,行业成熟方案覆盖范围广,从车载、工控、手持机都有涉及,且方案成熟。 近些年,Android以后来居上的态势,逐渐渗透至各行业领域,硬件手持大厂也把产品线重心向Android手持迁移,基于Android的行业解决方案越来越成熟,WinCE的开发人才流失,在WinCE解决方案上吃老本的企业寻求转型。
1532 0
xamarin开发android收集的一些工具
原文:xamarin开发android收集的一些工具 xamarin开发android收集的一些工具 工欲善其事,必先利其器,从16年下半年开始做xamarin相关的开发,平时使用的一些工具和google插件给大家分享一下,都有下载地址,持续更新。
1405 0
C# Xamarin For Android自动升级项目实战
一、课程介绍 “明人不说暗话,跟着阿笨一起玩Xamarin”,本次分享课程阿笨将带来大家一起学习Xamarin For Android系列《C# Xamarin For Android自动升级项目实战》。
2137 0
xamarin android网络请求总结
xamarin android中网络请求的框架非常多,在项目中使用的是第三方的一个网络请求框架restsharp,应该是github上.net网络请求最多star的框架,没有之一。这里就简单汇总了其他的一些网络请求的例子,主要还是分为android和.net两种平台。
1808 0
MVP架构在xamarin android中的简单使用
好几个月没写文章了,使用xamarin android也快接近两年,还有一个月职业生涯就到两个年了,从刚出来啥也不会了,到现在回头看这个项目,真jb操蛋(真辛苦了实施的人了,无数次吐槽怎么这么丑),怪自己太年轻了,还好是给指定行业的人使用。
1444 0
博客园app for xamarin android
碎碎念回顾2017 到了年底,坐在转椅上,望着窗外的雾霾......从16年6月走出校门,已经做了1年半的码农,成长不少,但总觉得进步得不够明显,虽然工资比刚来的时候涨了不少,但是还是觉得自己不够努力。
1622 0
+关注
操张林
文章
问答
视频
文章排行榜
最热
最新
相关电子书
更多
蚂蚁聚宝Android秒级编译——Freeline
立即下载
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
相关镜像