【问题标题】:Send push-notification using WebSockets after button click单击按钮后使用 WebSockets 发送推送通知
【发布时间】:2020-03-08 00:27:50
【问题描述】:

我非常接近在 C# 中实现一个系统,它允许我通过单击按钮从用 ASP.net 编写的界面向充当客户端的 C# 控制台应用程序发送推送通知。这一切都使用 WebSockets。

阅读大量教程并重用网上找到的代码后,我已经能够成功建立 WebSocket 连接。我还不能真正发送通知。

我正在努力解决的部分是单击按钮后立即触发的功能:

//Close ticket and send push-notification over websocket
public void Close(int id) {
    //Ticket ticket = mgr.GetTicket(id);

    //Create a new notification
    Notification notif = new Notification();
    notif.message = "Rofl test123 Notification lol";

    //Initialize WebSocketMiddleware here??
    //WebSocketsMiddleware wsm = new WebSocketsMiddleware(what parameter??);
    //wsm.Invoke(what HttpContext parameter???)

    NotificationManager notifMgr;
    //notifMgr.AddSubscriber(wsm);
    //notifMgr.SendNotificationAsync(notif);


    return;
}

我遇到的具体问题/问题是:

  1. 如何初始化类WebSocketsMiddleware?是否需要初始化,如果需要,RequestDelegate类型的参数是什么?我应该向该参数传递什么?
  2. WebSocketsMiddleware 有一个带有 HttpContext 类型参数上下文的 Invoke 函数。我只需要将new HttpContext() 传递给这个吗?够了吗?
  3. 有人做了一个类NotificationManager,这个类使用中间件来实际发送通知。我是否只需将初始化的 WebSocketsMiddleware 变量作为 NotificationManager.AddSubscriber() 的参数传递?那么每个客户端的通知会被很好地分开吗?
  4. 之后我可以使用 SendNotificationAsync() 发送通知吗?
  5. 额外问题:假设每个客户都有自己的按钮。当我单击客户的按钮时,只有该客户可能会收到推送通知。如何确保所有其他客户也不会收到相同的通知?

为了能够帮助我解决这些问题,您需要以下课程。问题只是关于 WebSockets,更多的是关于如何启动和使用我从教程中收集的类。

Notification.cs - 表示通知的类(通知文本、发送日期...):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SC.UI.MVC.Models
{
    public class Notification
    {
        public Guid? notificationId { get; set; }
        public int id { get; set; }
        public DateTime timestamp { get; set; }
        public string message { get; set; }
        public string type { get; set; }

        public Notification()
        {
            // add a new guid as a unique identifier for the notification in the db
            notificationId = Guid.NewGuid();
        }
    }
}

WebSocketsMiddleware.cs - 处理 WebSocket 的低级部分,调用连接等:

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;

namespace NotificationsApi.Notifications
{
    public class WebSocketsMiddleware
    {
        // private variable to track the next delegate to call in the request chain
        private readonly RequestDelegate _next;

        public WebSocketsMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            CancellationToken ct = context.RequestAborted;
            string currentSubscriberId = null;
            WebSocket currentSocket = null;

            // we want to listen on a specific path for websocket communications
            if (context.Request.Path == "/notifications/ws")
            {
                // make sure the request is a websocket request
                if (context.WebSockets.IsWebSocketRequest)
                {
                    currentSocket = await context.WebSockets.AcceptWebSocketAsync();
                    currentSubscriberId = NotificationManager.Instance.AddSubscriber(currentSocket);

                    // keep the socket open until we get a cancellation request
                    while (true)
                    {
                        if (ct.IsCancellationRequested)
                        {
                            break;
                        }
                    }
                }
                else // return an HTTP bad request status code if anything other a web socket request is made on this URI
                { 
                    context.Response.StatusCode = 400;
                }
            }

            // clean up the socket
            if (!string.IsNullOrWhiteSpace(currentSubscriberId))
            {
                NotificationManager.Instance.RemoveSubscriber(currentSubscriberId);
                if (currentSocket != null)
                {
                    await currentSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
                    currentSocket.Dispose();
                }
            }

            // call the next delegate in the pipeline
            await _next(context);
            return;
        }
    }
}

NotificationManager.cs - 具有添加和删除订阅者以及实际发送通知的三个功能的接口/类。使用 WebSocket 中间件来实现:

using SC.UI.MVC.Models;
//using NotificationsApi.Persistence;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NotificationsApi.Notifications
{
    // interface for NotificationManager for dependency injection
    public interface INotificationManager
    {
        string AddSubscriber(WebSocket subscriber);
        void RemoveSubscriber(string subscriberId);
        Task SendNotificationAsync(Notification notification);
    }

    public class NotificationManager : INotificationManager 
    {
        // static instance of the NotificationManager class
        private static INotificationManager _instance;
        public static INotificationManager Instance { get { return _instance ?? (_instance = new NotificationManager()); } set { _instance = value; } }

        // static dictionary to keep track of all notification subscribers
        private static ConcurrentDictionary<string, WebSocket> _subscribers = new ConcurrentDictionary<string, WebSocket>();

        // adds a subscriber to receive notifications
        public string AddSubscriber(WebSocket subscriber)
        {
            var subscriberId = Guid.NewGuid().ToString();
            _subscribers.TryAdd(subscriberId, subscriber);
            return subscriberId.ToString();
        }

        // removes a notifications subscriber
        public void RemoveSubscriber(string subscriberId)
        {
            WebSocket empty;
            _subscribers.TryRemove(subscriberId, out empty);
        }

        // sends a notification to all subscribers
        public async Task SendNotificationAsync(Notification notification)
        {
            // add the notification to the persistence store
            //await PersistenceManager.Instance.AddNotificationAsync(notification);

            // send the notification to all subscribers
            foreach (var s in _subscribers)
            {
                if (s.Value.State == WebSocketState.Open)
                {
                    var jsonNotification = JsonConvert.SerializeObject(notification);
                    await SendStringAsync(s.Value, jsonNotification);
                }
            }
        }

        // sends a string via web socket communication
        private async Task SendStringAsync(WebSocket socket, string data, CancellationToken ct = default(CancellationToken))
        {
            var buffer = Encoding.UTF8.GetBytes(data);
            var segment = new ArraySegment<byte>(buffer);
            await socket.SendAsync(segment, WebSocketMessageType.Text, true, ct);
        }
    }
}

Client.cs - 接收推送通知的客户端。我猜这里不是问题:

    /* WEBSOCKET PART */
    //Variables for websocket
    private static object consoleLock = new object();
    private const int sendChunkSize = 256;
    private const int receiveChunkSize = 256;
    private const bool verbose = true;
    private static readonly TimeSpan delay = TimeSpan.FromMilliseconds(30000);

    //Function to check if a ticket from this client is closed/solved
    public void checkTicketSolved() {
        Thread.Sleep(1000);
        Connect("ws://localhost:5050/notifications/ws").Wait();
        Console.WriteLine("Press any key to exit...");
    }

    public static async Task Connect(string uri)
    {
        ClientWebSocket webSocket = null;

        try
        {
            webSocket = new ClientWebSocket();
            await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
            await Task.WhenAll(Receive(webSocket), Send(webSocket));
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex);
        }
        finally
        {
            if (webSocket != null)
                webSocket.Dispose();
            Console.WriteLine();

            lock (consoleLock)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("WebSocket closed.");
                Console.ResetColor();
            }
        }
    }
   static UTF8Encoding encoder = new UTF8Encoding();

    private static async Task Send(ClientWebSocket webSocket)
    {

        //byte[] buffer = encoder.GetBytes("{\"op\":\"blocks_sub\"}"); //"{\"op\":\"unconfirmed_sub\"}");
        byte[] buffer = encoder.GetBytes("{\"op\":\"unconfirmed_sub\"}");
        await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);

      while (webSocket.State == WebSocketState.Open)
        {
            LogStatus(false, buffer, buffer.Length);
            await Task.Delay(delay);
        }
    }

    private static async Task Receive(ClientWebSocket webSocket)
    {
        byte[] buffer = new byte[receiveChunkSize];
        while (webSocket.State == WebSocketState.Open)
        {
            var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            if (result.MessageType == WebSocketMessageType.Close)
            {
                await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
            }
            else
            {
                LogStatus(true, buffer, result.Count);
            }
        }
    }

    private static void LogStatus(bool receiving, byte[] buffer, int length)
    {
        lock (consoleLock)
        {
            Console.ForegroundColor = receiving ? ConsoleColor.Green : ConsoleColor.Gray;
            //Console.WriteLine("{0} ", receiving ? "Received" : "Sent");

            if (verbose)
                Console.WriteLine(encoder.GetString(buffer));

            Console.ResetColor();
        }
    }
}

您也可以在Github 上找到此代码。 相关部分代码位于:

  • WebServer/UI-MVC/Controllers/TicketController.cs -> 包含点击按钮时触发的函数。
  • WebServer/UI-MVC/Notifications -> 包含 NotificationManager.cs 和 WebSocketsMiddleware.cs
  • WebServer/UI-MVC/Models -> 包含 Notification.cs
  • Client/ 包含客户端控制台应用程序的所有代码

为您提供有关该应用程序的一些背景信息: 这个应用程序代表一个票务系统,它允许使用我的软件的客户/客户打开支持票。 WebServer 部分供我的管理员/员工回答和管理工单。控制台应用程序是我的客户/客户需要安装的,以便联系我的支持服务并打开支持票证。当管理员通过单击按钮关闭客户的票证时,这意味着票证,因此客户的问题已解决并关闭。导致客户端收到关于此的推送通知。

我不是在寻找有关 WebSockets 的其他教程的参考资料或使用 SignalR 的建议或其他任何东西,我已经阅读了所有这些,并且我已经使用了 SignalR,但现在对纯 WebSockets 感兴趣。如果有人可以帮助我解决此问题中发布的第一部分代码(关闭函数)并解释他所做的事情,我将非常感激。谢谢!

【问题讨论】:

  • 用于教育目的。我们必须研究一些具体的技术并实施它们。我选择了 SignalR 和 Websockets。我必须同时使用它们,已经成功实现了 SignalR。现在接近 WebSockets。

标签: c# asp.net websocket


【解决方案1】:

我自己找到了解决方案。

首先我创建了一个名为 NotificationsController.cs

的新控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SC.UI.MVC.Models;
using NotificationsApi.Notifications;
//using NotificationsApi.Persistence;
using System.Net.Http;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace NotificationsApi.Controllers
{
    [Route("api/notifications")]
    public class NotificationsController : Controller
    {
        // GET api/notifications
        [HttpGet]
        public ActionResult Get()
        {
            try
            {
                var notifications = new List<Notification>();
                //notifications = PersistenceManager.Instance.GetNotifications();
                return Ok(notifications);
            }
            catch (Exception exception)
            {
                // log exception
                // TODO: implement logging

                // return a 500
                return StatusCode(500);
            }
        }

        // POST api/notifications
        [HttpPost]
        public async Task<ActionResult> Post(string message)
        {

            Notification notification = new Notification();
            notification.message = message;

            Console.WriteLine(message);

            try
            {
                // return a 400 if we didn't get a valid json payload in the body
                if (notification == null)
                    return BadRequest();

                await NotificationManager.Instance.SendNotificationAsync(notification);

                // we aren't returning the object to reference because POSTing a notification is fire and forget
                return Created(string.Empty, null);
            }
            catch (Exception exception)
            {
                // log the error
                // TODO: implement logging

                // return a 500
                return StatusCode(500);
            }

            return Ok();
        }
    }
}

然后我注释掉了 Notification.cs 中不必要的属性,因此只保留了 Guid 和消息。现在我可以通过使用带有消息参数作为数据的 POST 请求调用 NotificationsController 来发送通知。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2017-11-05
    • 2019-06-11
    • 2023-03-04
    • 2021-03-22
    • 1970-01-01
    相关资源
    最近更新 更多