阅读量:0
在C#中实现消息推送功能,可以使用WebSocket技术。WebSocket是一种网络通信协议,它允许在客户端和服务器之间建立实时、双向的通信。以下是一个简单的示例,展示了如何在C#中使用WebSocket实现消息推送功能:
- 首先,确保你的项目中已经安装了
System.Net.WebSockets
命名空间。如果没有安装,可以通过NuGet包管理器进行安装:
Install-Package System.Net.WebSockets -Version 4.5.2
- 创建一个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); } } }
- 创建一个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服务器端和客户端示例。当客户端连接到服务器并发送一条消息时,服务器会将接收到的消息广播给所有连接的客户端。