ASP.NET Core SignalR.NET 客户端

一、ASP.NET Core SignalR.NET 客户端

Asp.Net Core3.1的SignalR服务端应用,目前仅可以对接PC桌面版本的.Net Core 引用。

 

二、使用方式

1.创建 .Net Core wpf引用

2.安装客户端包

Install-Package Microsoft.AspNetCore.SignalR.Client

3.链接服务器

  public partial class MainWindow : Window
    {
        HubConnection connection;
        public MainWindow()
        {
            InitializeComponent();

            connection = new HubConnectionBuilder()
                .WithUrl("http://localhost:53353/ChatHub")
                .Build();

            connection.Closed += async (error) =>
            {
                await Task.Delay(new Random().Next(0,5) * 1000);
                await connection.StartAsync();
            };
        }

        private async void connectButton_Click(object sender, RoutedEventArgs e)
        {
            connection.On("ReceiveMessage", (user, message) =>
            {
                this.Dispatcher.Invoke(() =>
                {
                   var newMessage = $"{user}: {message}";
                   messagesList.Items.Add(newMessage);
                });
            });

            try
            {
                await connection.StartAsync();
                messagesList.Items.Add("Connection started");
                connectButton.IsEnabled = false;
                sendButton.IsEnabled = true;
            }
            catch (Exception ex)
            {
                messagesList.Items.Add(ex.Message);
            }
        }

        private async void sendButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                await connection.InvokeAsync("SendMessage", 
                    userTextBox.Text, messageTextBox.Text);
            }
            catch (Exception ex)
            {                
                messagesList.Items.Add(ex.Message);                
            }
        }
    }

4.断开处理

connection.Closed += async (error) =>
{
    await Task.Delay(new Random().Next(0,5) * 1000);
    await connection.StartAsync();
};

 

更多:

 Asp.Net Core 3.1 SignalR 启动配置变化

 Asp.Net Core 2.0使用SignalR技术-入门

 Asp.Net Core SignalR获取集线器实例,从集线器外部发送消息

你可能感兴趣的:(Asp.net,SignalR)