zoukankan      html  css  js  c++  java
  • [置顶] Xamarin android中使用signalr实现即时通讯

    前面几天也写了一些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入门例子

  • 相关阅读:
    犹太人高成就的秘诀
    EXSI宿主机更换硬盘后虚机启动有问题
    Centos7 系统启动docker报错 inotify add watch failed
    Gluster的搭建和使用
    关于HA(2.102 -2.103 服务器排障)
    Fabric的简介
    关于CPU的一些操作(CPU设置超频)
    docker的安装和技巧
    linux 下查看wwn号
    HP 3par多路径安装方法
  • 原文地址:https://www.cnblogs.com/zhangmumu/p/7374790.html
Copyright © 2011-2022 走看看