[原创]c# asp.net core signlR推送 基于w

2023-04-09  本文已影响0人  吉凶以情迁

服务端

<PackageReference Include="Microsoft.AspNetCore.SignalR" Condition="$(DefineConstants.Contains('PUSH'))" Version="1.1.0" />


builder.Services.AddSignalR();

//在use路由之后使用如下
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<NotificationHub>("/notificationhub");
});
 public class NotificationHub : Hub
    {
        /*   public async Task SendNotification(string message)
           {
               await Clients.All.SendAsync("ReceiveNotification", message);
           }*/

        private readonly IHubContext<NotificationHub> _hubContext;

        public NotificationHub(IHubContext<NotificationHub> hubContext)
        {
            _hubContext = hubContext;
        }

      /*  public NotificationHub()
        {
        }*/

        public async Task SendUserMessage(string user, string message)
        {
            // 插入数据库

            // 通知所有客户端有新消息
            var context = Context;
            var connectionId = context.ConnectionId;
            Console.WriteLine($"SendUserMessage转发来自{ connectionId}客户端消息,用户{user}:{message}" );
            await Clients.All.SendAsync("ReceiveUserMessage", user, message);
        }

        public async Task SendMessage( string message)
        {
            // 插入数据库

            // 通知所有客户端有新消息
            var context = Context;
            var connectionId = context.ConnectionId;
            Console.WriteLine($"SendMessage方法转发来自{connectionId}客户端消息,用户:{message}");
            await Clients.All.SendAsync("ReceiveMessage",message);
        }

        public async Task SendMessageToClient(string clientId, string message)
        {
            var context = Context;
            var connectionId = context.ConnectionId;
            Console.WriteLine("SendMessageToClient转发来自" + connectionId + "客户端消息,委托发送给" + clientId + ",message:"+message);
            await _hubContext.Clients.Client(clientId).SendAsync("ReceiveMessageFromClient", connectionId, message);
        }
    }

客户端

经过测试要跑通,必须降级,否则没有那个方法WithUrl
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="3.1.0" />
如果不依赖这个那么和服务端那边连不上,显示404.

using Microsoft.AspNetCore.SignalR.Client;

using System.Configuration;
using System.Data.Common;
using System.Net;



     var hubConnection = new HubConnectionBuilder().WithUrl(domain + "/notificationHub")
                     .Build();

        //var hubProxy = hubConnection.CreateHubProxy("NotificationHub");

        hubConnection.On<string>("ReceiveMessage", message =>
        {
            Console.WriteLine("ReceiveMessage收到消息:" + message);
        });

        hubConnection.On<string,string>("ReceiveUserMessage", (user, message )=>
        {
            Console.WriteLine("收到ReceiveUserMessage:" + user+"消息:" + message);
        });

        hubConnection.On("ReceiveUserMessage", new Action<dynamic, dynamic>((name, message) =>
        {
            Console.WriteLine($"ReceiveUserMessage: {name}: {message}");
        }));

        hubConnection.On<string, string>("ReceiveMessageFromClient", (clientid,message) =>
        {
            Console.WriteLine($"ReceiveMessageFromClient: client:{clientid}, {message}");
        });

  try
                {
                    hubConnection.StartAsync().Wait();
                    connected = true;
                    connectionId = hubConnection.ConnectionId;
                    Console.WriteLine($"Connect Succ, Client Id  {connectionId}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Failed to connect to {domain}: {ex.Message}");
                    Console.WriteLine($"Retrying in 5 seconds...");
                    Thread.Sleep(5000);
                }

这个signal可以客户端给服务器发消息 服务器给客户端发消息, 上面的例子是收到客户端消息后又转发消息, 客户端也可以直接调用
如下


                    // 发送消息给服务器端
                    hubConnection.SendAsync("SendMessage", "Hello, server!");
                    hubConnection.SendAsync("SendUserMessage", "用户1","Hello, server!");

                    // 发送消息给特定客户端
                     hubConnection.SendAsync("SendMessageToClient", connectionId, "Hello, client1!");

                    hubConnection.InvokeAsync("SendMessage", "--客户端直接调用!"+temp);

其中hubConnection.InvokeAsync是直接调用,但是依然能收到

image.png

服务端部署客户端免集成推送接口

        [HttpPost("send")]
        public async Task<IActionResult> SendUserMessage(string user, string message)
        {
            // 处理消息逻辑
            // ...
            // 发送消息给所有客户端
            await _hubContext.Clients.All.SendAsync("ReceiveUserMessage", user, message);
            await _hubContext.Clients.All.SendAsync("ReceiveMessage", message);
            return Ok("发送完成");
        }

服务端开启日志

  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft.AspNetCore.SignalR": "Debug",
      "Microsoft.AspNetCore.Http.Connections": "Debug",
      "Microsoft": "Information"
    }
  },
image.png
上一篇下一篇

猜你喜欢

热点阅读