前言
我之前稍微研究了一下SignalR Core。用起來還行。簡單來說SignalR就是用來解決實時通訊的問題的。
ASP.NET Core SingleR:初次體驗和簡單項目搭建
SignalR支持三種客戶端,C#,Java,JavaScirpt?;緣蛴昧?。本身就是微軟開發(fā)的,肯定支持自己的語言。因為是Websocket的上層封裝,所以也要支持Websocket的主要客戶,JavaScirpt。不過我沒想到有Java版本的,那這樣雙語言互通的問題也就解決了。
環(huán)境
- .net core 8.0
- visual studio 2022
Webapi開發(fā)測試
服務端開發(fā)
我們新建一個WebApi
按照我之前設置的
.NET Core webapi 從零開始在IIS上面發(fā)布后端接口
再添加一下上次添加的聊天室代碼
ASP.NET Core SingleR:初次體驗和簡單項目搭建
Program.cs
var builder = WebApplication.CreateBuilder(args);
//配置跨域
var MyPolicy = "MyPolicy";
builder.Services.AddCors(options =>
{
options.AddPolicy(MyPolicy, policy =>
{
policy.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod();
});
});
//啟用SignalR
builder.Services.AddSignalR();
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
//添加swagger接口配置
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "API標題",
Description = $"API描述,v1版本"
});
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
//IncludeXmlComments 第二參數(shù) true 則顯示 控制器 注釋
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename), true);
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
}
app.UseSwagger();
app.UseSwaggerUI();
//自動重定向到swgger文件
app.UseStatusCodePagesWithRedirects("/swagger/index.html");
app.UseCors(MyPolicy);
app.UseHttpsRedirection();
app.UseAuthorization();
//SignalR位置
app.MapHub<ChatHub>("/ChatHub");
app.MapControllers();
app.Run();
ChatHub
using Microsoft.AspNetCore.SignalR;
namespace SiganlRTest.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
客戶端開發(fā)
官方文檔
ASP.NET Core SignalR .NET 客戶端
為了方便操作的實時性,我們新建一個WPF程序
微軟官方示例代碼
新建項目
Nuget添加
添加代碼
MainWindow.xaml
<Window x:Class="SignalR_WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SignalR_WPF"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800">
<Grid Margin="0,0,193.333,50.667">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="109*" />
<ColumnDefinition Width="288*" />
</Grid.ColumnDefinitions>
<Button x:Name="connectButton"
Content="Connect"
HorizontalAlignment="Left"
Margin="275.333,63,0,0"
VerticalAlignment="Top"
Width="95"
Click="connectButton_Click"
Height="41"
Grid.Column="1" />
<Button x:Name="sendButton"
Content="Send Message"
HorizontalAlignment="Left"
Margin="275.333,113,0,0"
VerticalAlignment="Top"
Width="95"
Click="sendButton_Click"
Height="41"
Grid.Column="1"
IsEnabled="False" />
<TextBox x:Name="messageTextBox"
HorizontalAlignment="Left"
Height="41"
Margin="82,113,0,0"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="311"
Grid.ColumnSpan="2" />
<ListBox x:Name="messagesList"
HorizontalAlignment="Left"
Height="141"
Margin="82,170,0,0"
VerticalAlignment="Top"
Width="311"
RenderTransformOrigin="-0.304,0.109"
BorderThickness="1"
Grid.ColumnSpan="2"
BorderBrush="Gainsboro" />
<TextBox x:Name="userTextBox"
HorizontalAlignment="Left"
Height="41"
Margin="82,57,0,0"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="311"
Grid.ColumnSpan="2" />
<Label Content="User"
HorizontalAlignment="Left"
Height="31"
Margin="39,63,0,0"
VerticalAlignment="Top"
Width="38" />
<Label Content="Message"
HorizontalAlignment="Left"
Height="26"
Margin="19,120,0,0"
VerticalAlignment="Top"
Width="58" />
</Grid>
</Window>
MainWindow.xaml.cs
using Microsoft.AspNetCore.SignalR.Client;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace SignalR_WPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
HubConnection connection;
public MainWindow()
{
InitializeComponent();
connection = new HubConnectionBuilder()
.WithUrl("http://localhost:53353/ChatHub")
.Build();
#region snippet_ClosedRestart
connection.Closed += async (error) =>
{
await Task.Delay(new Random().Next(0, 5) * 1000);
await connection.StartAsync();
};
#endregion
}
private async void connectButton_Click(object sender, RoutedEventArgs e)
{
#region snippet_ConnectionOn
connection.On<string, string>("ReceiveMessage", (user, message) =>
{
this.Dispatcher.Invoke(() =>
{
var newMessage = $"{user}: {message}";
messagesList.Items.Add(newMessage);
});
});
#endregion
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)
{
#region snippet_ErrorHandling
try
{
#region snippet_InvokeAsync
await connection.InvokeAsync("SendMessage",
userTextBox.Text, messageTextBox.Text);
#endregion
}
catch (Exception ex)
{
messagesList.Items.Add(ex.Message);
}
#endregion
}
}
}
運行結果
代碼解析
SignalR的代碼將服務器的輸入和輸出分為兩類:
- 輸入:類似于Http的接口
- 輸出:類似于Http的回調,因為SignalR的數(shù)據是通關另一個口進行返回的
服務端
客戶端
所以我們一般的代碼邏輯文章來源:http://www.zghlxwxcb.cn/news/detail-807884.html
- 監(jiān)聽所有的回調
- 嘗試連接
- 連接成功,發(fā)送接口
- 服務器返回回調,回調到監(jiān)聽的接口
總結
我們目前是單接口,單回調。收發(fā)數(shù)據,那還是比較簡單。那么如果我們想對SignalR的接口進行復雜的調用呢?下篇文章我會對這個進行思考和探索。文章來源地址http://www.zghlxwxcb.cn/news/detail-807884.html
到了這里,關于ASP.NET Core SingleR Core:WebApi + .net 客戶端開發(fā)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!