web基于SingleR进行即时通讯

参考文档如下:

1.WebSocket教程

2..net后端使用SignalR定时向前端vue推送消息

3.教程:ASP.NET Core SignalR 入门

4.ASP.NET Core SingleR Core:WebApi + .net 客户端开发

5..net core3.1 教程+sqlsugar .net core singler

6.Asp.net core mvc项目发布及iis配置记录

正式开始...

(1)开始服务端的设计

1.创建web项目,无需多言

2.在项目上添加SignalR客户端库 

在“解决方案资源管理器”>中,右键单击项目,然后选择“添加”“客户端库”。

在“添加客户端库”对话框中:

  • 为“提供程序”选择“unpkg”
  • 对于“库”,请输入 @microsoft/signalr@latest
  • 选择“选择特定文件”,展开“dist/browser”文件夹,然后选择 signalr.js 和 signalr.min.js
  • 将“目标位置”设置为 wwwroot/js/signalr/
  • 选择“安装” 。

 3.创建SignalR中心

创建 Hubs 文件夹,在 Hubs 文件夹中,使用以下代码创建 ChatHub 类:

using Microsoft.AspNetCore.SignalR;

namespace SignalRChat.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

中心是一个类,用作处理客户端 - 服务器通信的高级管道。可通过已连接客户端调用 SendMessage,以向所有客户端发送消息

4.配置SignalR客户端

Program.cs 文件中添加标有“这句的代码”

using SignalRChat.Hubs;//这句

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddSignalR();//这句

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();
app.MapHub<ChatHub>("/chatHub");//这句

app.Run();
View Code

(2)添加SignalR客户端代码,这个客户端有wpf等桌面应用还有web页面

1.wpf作为客户端

 

在MainWindow.xmal中创建以下界面元素

<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>   
View Code

 在MainWindow.xmal.cs中设计如下

public partial class MainWindow : Window
{
    HubConnection connection;
    public MainWindow()
    {
        InitializeComponent();
        connection = new HubConnectionBuilder()
            .WithUrl("http://192.168.1.101:8000/ChatHub").Build();//http://192.168.1.101:8000这是服务端发布之后的地址

        #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
    }
}
View Code

2.Web中一个页面作为客户端

根据参考文档2。

(1)首先安装:npm install @microsoft/signalr

(2)然后导入:import * as signalR from "@aspnet/signalr"

(3)写接收程序

created() {
      let thisVue = this;
      this.connection = new signalR.HubConnectionBuilder()
          .withUrl("http://localhost:52789/chathub", {
            skipNegotiation: true,
            transport: signalR.HttpTransportType.WebSockets,
          })
          .configureLogging(signalR.LogLevel.Information)
          .build();

      this.connection.on("ReceiveMessage", function (user, message) {
        thisVue.messages.push({ user, message });
        thisVue.msg = message;
        thisVue.$alert(message, '提示', {
          confirmButtonText: '确定',
          // eslint-disable-next-line no-unused-vars
          callback: action => {
            /*this.$message({
              type: 'info',
              message: `action: ${ action }`
            });*/
          }
        });
      });
      this.connection.start();

},
View Code

 

posted @ 2024-03-30 20:04  HelloWorld庄先生  阅读(125)  评论(0编辑  收藏  举报