在C#中實現消息推送功能,可以使用WebSocket技術。WebSocket是一種網絡通信協議,它允許在客戶端和服務器之間建立實時、雙向的通信。以下是一個簡單的示例,展示了如何在C#中使用WebSocket實現消息推送功能:
System.Net.WebSockets
命名空間。如果沒有安裝,可以通過NuGet包管理器進行安裝:Install-Package System.Net.WebSockets -Version 4.5.2
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);
}
}
}
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服務器端和客戶端示例。當客戶端連接到服務器并發送一條消息時,服務器會將接收到的消息廣播給所有連接的客戶端。