91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

c#中如何實現消息推送功能

c#
小樊
96
2024-09-28 01:28:01
欄目: 編程語言

在C#中實現消息推送功能,可以使用WebSocket技術。WebSocket是一種網絡通信協議,它允許在客戶端和服務器之間建立實時、雙向的通信。以下是一個簡單的示例,展示了如何在C#中使用WebSocket實現消息推送功能:

  1. 首先,確保你的項目中已經安裝了System.Net.WebSockets命名空間。如果沒有安裝,可以通過NuGet包管理器進行安裝:
Install-Package System.Net.WebSockets -Version 4.5.2
  1. 創建一個WebSocket服務器端示例:
using System;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;

namespace WebSocketServer
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string uri = "ws://localhost:8080";

            using (var server = new WebSocketServer(uri))
            {
                server.MessageReceived += Server_MessageReceived;
                await server.Start();
                Console.WriteLine("WebSocket server started.");

                Console.ReadLine();
            }
        }

        private static async Task Server_MessageReceived(object sender, WebSocketMessageReceivedEventArgs e)
        {
            WebSocket webSocket = e.WebSocket;
            byte[] buffer = new byte[e.Message.Length];
            await e.Message.ReadAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            string message = Encoding.UTF8.GetString(buffer);

            Console.WriteLine($"Received message: {message}");

            // 廣播消息給所有連接的客戶端
            await BroadcastMessageAsync(message);
        }

        private static async Task BroadcastMessageAsync(string message)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(message);

            foreach (var webSocket in WebSocketServer.Connections)
            {
                if (webSocket.State == WebSocketState.Open)
                {
                    await webSocket.SendAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                }
            }
        }
    }

    public class WebSocketServer
    {
        private readonly string _uri;
        private readonly List<WebSocket> _connections = new List<WebSocket>();

        public event EventHandler<WebSocketMessageReceivedEventArgs> MessageReceived;

        public WebSocketServer(string uri)
        {
            _uri = uri;
        }

        public async Task Start()
        {
            var listener = new HttpListener();
            listener.Prefixes.Add(_uri);
            listener.OnMessageReceived += Listener_OnMessageReceived;
            listener.Start();

            while (true)
            {
                var context = await listener.AcceptAsync();
                var webSocket = new WebSocket(context);
                _connections.Add(webSocket);

                webSocket.OnMessageReceived += WebSocket_OnMessageReceived;
                webSocket.OnClose += WebSocket_OnClose;

                await webSocket.AcceptAsync();
            }
        }

        private async Task Listener_OnMessageReceived(object sender, HttpListenerContext context)
        {
            var webSocket = new WebSocket(context);
            _connections.Add(webSocket);

            webSocket.OnMessageReceived += WebSocket_OnMessageReceived;
            webSocket.OnClose += WebSocket_OnClose;

            await webSocket.AcceptAsync();
        }

        private async Task WebSocket_OnMessageReceived(object sender, WebSocketMessageReceivedEventArgs e)
        {
            MessageReceived?.Invoke(this, e);
        }

        private async Task WebSocket_OnClose(object sender, WebSocketCloseStatus closeStatus, string reason, bool isTerminated)
        {
            var webSocket = (WebSocket)sender;
            _connections.Remove(webSocket);
        }
    }
}
  1. 創建一個WebSocket客戶端示例:
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;

namespace WebSocketClient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string uri = "ws://localhost:8080";

            using (var webSocket = new WebSocket(uri))
            {
                webSocket.MessageReceived += WebSocket_MessageReceived;
                await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);

                Console.WriteLine("Connected to WebSocket server.");

                await SendMessageAsync("Hello, WebSocket server!");

                Console.ReadLine();
            }
        }

        private static async Task WebSocket_MessageReceived(object sender, WebSocketMessageReceivedEventArgs e)
        {
            string message = Encoding.UTF8.GetString(e.Message.ToArray());
            Console.WriteLine($"Received message: {message}");
        }

        private static async Task SendMessageAsync(string message)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(message);
            await webSocket.SendAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        }
    }
}

現在,你可以分別運行WebSocket服務器端和客戶端示例。當客戶端連接到服務器并發送一條消息時,服務器會將接收到的消息廣播給所有連接的客戶端。

0
东兴市| 军事| 大兴区| 大余县| 左云县| 清原| 保德县| 丽江市| 海城市| 津南区| 漯河市| 林芝县| 友谊县| 峡江县| 加查县| 张家口市| 夏邑县| 韶关市| 南华县| 榆中县| 华宁县| 巫山县| 松滋市| 垫江县| 自贡市| 瑞昌市| 宝山区| 疏附县| 宜宾市| 鄂托克前旗| 眉山市| 六安市| 冀州市| 彭州市| 佛教| 孟州市| 元江| 安丘市| 沿河| 泰州市| 梅州市|