首页 > 其他分享 >SignalR即时通讯 :WPF+Xamarin.Android

SignalR即时通讯 :WPF+Xamarin.Android

时间:2022-10-29 17:22:14浏览次数:52  
标签:return string message public SignalR connection WPF Android

1、背景介绍

PDA操作物料出入库信息投送到大屏显示

2、WPF服务端

添加OWINMicrosoft.AspNet.SignalR.Core引用

2.1、创建启动类

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCors(CorsOptions.AllowAll);
        app.MapSignalR();
    }
}

2.2、创建Hub实现类

public class ServiceHub : Hub
{
    public void Send(string name, string message)
    {
        Clients.All.addMessage(name, message);
    }
    public override Task OnConnected()
    {
        Application.Current.Dispatcher.Invoke(() =>
            ((MainWindow)Application.Current.MainWindow).WriteToConsole("Client connected: " + Context.ConnectionId));
        return base.OnConnected();
    }
    public override Task OnDisconnected(bool ss)
    {
        Application.Current.Dispatcher.Invoke(() =>
            ((MainWindow)Application.Current.MainWindow).WriteToConsole("Client disconnected: " + Context.ConnectionId));
        return base.OnDisconnected(ss);
    }
}

2.3、启动、关闭服务

public partial class MainWindow : Window
{
    public IDisposable SignalR { get; set; }
    public MainWindow()
    {
        InitializeComponent();
    }
    /// <summary>
    /// Calls the StartServer method with Task.Run to not
    /// block the UI thread. 
    /// </summary>
    private void ButtonStart_Click(object sender, RoutedEventArgs e)
    {
        WriteToConsole("Starting server...");
        ButtonStart.IsEnabled = false;
        Task.Run(() => StartServer());
    }
    /// <summary>
    /// Stops the server and closes the form. Restart functionality omitted
    /// for clarity.
    /// </summary>
    private void ButtonStop_Click(object sender, RoutedEventArgs e)
    {
        SignalR.Dispose();
        Close();
    }
    /// <summary>
    /// Starts the server and checks for error thrown when another server is already 
    /// running. This method is called asynchronously from Button_Start.
    /// </summary>
    private void StartServer()
    {
        string ServerURI = ConfigurationManager.AppSettings["serviceUri"];
        try
        {
            SignalR = WebApp.Start(ServerURI);
        }
        catch (TargetInvocationException)
        {
            WriteToConsole("A server is already running at " + ServerURI);
            this.Dispatcher.Invoke(() => ButtonStart.IsEnabled = true);
            return;
        }
        this.Dispatcher.Invoke(() => ButtonStop.IsEnabled = true);
        WriteToConsole("Server started at " + ServerURI);
    }
    ///This method adds a line to the RichTextBoxConsole control, using Dispatcher.Invoke if used
    /// from a SignalR hub thread rather than the UI thread.
    public void WriteToConsole(String message)
    {
        if (!(RichTextBoxConsole.CheckAccess()))
        {
            this.Dispatcher.Invoke(() =>
                WriteToConsole(message)
            );
            return;
        }
        RichTextBoxConsole.AppendText(message + "\r");
    }
}

3、Xamarin发送端

引用 Microsoft.AspNet.SignalR.Client

public class SignalrChatClient
{
    private readonly HubConnection _connection;
    private readonly IHubProxy _proxy;//客户端代理服务器端中心
    public static SignalrChatClient CurrentClient;
    public static SignalrChatClient SignalrChatClientBuild(string serverIp)
    {
        if (CurrentClient == null)
        {
            CurrentClient = new SignalrChatClient(serverIp);
        }
        return CurrentClient;
    }

    private SignalrChatClient(string serverIp)
    {
        _connection = new HubConnection(serverIp);
        _proxy = _connection.CreateHubProxy("ServiceHub");
    }

    //负责连接的方法
    public async Task<string> Connect()
    {
        if (_connection != null)
        {
            if (_connection.State != ConnectionState.Connected)
            {
                try
                {
                    await _connection.Start();
                    return "Y";
                }
                catch
                {
                    return "SignalR服务连接失败+" + _connection.Url;
                }
            }
        }
        return "SignalR连接对象为空:" + _connection.Url;
    }

    //负责发送的方法
    public Task Send(string message)
    {
        string serverMethod = "Send";
        if (_connection != null)
        {
            if (_connection.State != ConnectionState.Connected)
            {
                return null;
            }
            if (_proxy != null)
            {
                return _proxy.Invoke(serverMethod, "test", message);
            }
        }
        return null;
    }
}

4、WPF大屏接收端

引用 Microsoft.AspNet.SignalR.Client

private async void ConnectAsync()
{
    string ServerURI = ConfigurationManager.AppSettings["serviceUri"];
    Connection = new HubConnection(ServerURI);
    Connection.Closed += Connection_Closed;
    HubProxy = Connection.CreateHubProxy("ServiceHub");
    HubProxy.On<string, string>("AddMessage", (name, message) =>
        //接收到数据后的处理逻辑
    );
    try
    {
        await Connection.Start();
    }
    catch (HttpRequestException)
    {
        StatusText.Content = "Unable to connect to server: Start server before connecting clients.";
        return;
    }
}

特别注意

  • 服务端、客户端SignalR版本需要保持一致,否则无法连接
  • 相应端口需要开放,否则无法连接

标签:return,string,message,public,SignalR,connection,WPF,Android
From: https://www.cnblogs.com/hklol/p/16839158.html

相关文章

  • 【WPF】命中测试(Hitest) 开篇
       命中测试支持VisualTreeHelper类中HitTest方法的用途是确定几何或点坐标值是否在给定对象的呈现内容内,如控件或图形元素。例如,可以使用命中测试确定对象边框......
  • 【WPF】Hitest 命中测试
    概述: WPF中的Canvas是常用的一个绘图控件,可以方便地在Canvas中添加我们需要处理的各种元素如:图片、文字等。但Canvas中元素增加到一定数量,并且有重合的时候,我们如何通过......
  • 【WPF】绘制图形的三种方法及区别
     WPF中用于绘图的类主要有三个,分别是Shape类、Drawing类和DrawingVisual类,Shape类存在于System.Windows.Shapes命,而Drawing类和DrawingVisual类则都存在于System.Window......
  • wpf .net core win7 独立运行补丁安装记录
     Windows7系统上,根据dotnet官方文档,需要安装上KB2533623补丁方案如下:首先使用 fx2.0 写一个启动器 如果检测可以运行则拉起.net core 主程序 否则弹出命令......
  • Android内嵌Unity开发简单的3D动态模型
    Unity端就不仔细说了,下面主要讲Unity打包出来在Androidstudio后的操作.DEMO地址:Stringf/UnityAndroid3DModel(github.com)Unity打包Android项目:unityLibrary包bu......
  • 如何用界面组件DevExpress WPF创建Excel式的过滤功能?赶紧Get
    DevExpressWPF拥有120+个控件和库,将帮助您交付满足甚至超出企业需求的高性能业务应用程序。通过DevExpressWPF能创建有着强大互动功能的XAML基础应用程序,这些应用程序专......
  • 【Termux】 Android 模拟终端组合键操作说明
    以下均来自谷歌翻译: 使用CLI终端需要使用Alt,Ctrl,Esc等键。Termux触摸键盘不包括一个。为此,Termux使用Volumedown按钮模拟Ctrl键。例如,Volumedown+L在触摸键盘上按下}会......
  • 【WPF】ToolBar工具栏菜单和命令
     ToolBar   对许多小的按钮(或者其他控件)进行分组。   ToolBar可以被放在元素树的任何地方,但是通常把它们放在一个叫作ToolBarTray的FrameworkElement中。  ......
  • Android Studio生成.jks文件
    jks(javakeystore)字面意思可以理解为java的密钥库,是一个用来存放密钥和证书的仓库。而keytool就是密钥和证书的管理工具,它把key(密钥)和certificate(证书)存放在一个叫keysto......
  • 傻瓜式android studio升级方式
     使用ToolBox下载地址https://www.jetbrains.com/toolbox-app/ 参考:https://blog.csdn.net/qq_29752857/article/details/107052986 ......