要實現C# WebSocket服務器與客戶端通信,您可以使用.NET的WebSocket庫來創建WebSocket服務器和客戶端。以下是一個簡單的示例代碼,演示了如何在C#中實現WebSocket服務器和客戶端之間的通信:
WebSocket服務器端代碼示例:
using System;
using System.Net;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
while (true)
{
var context = await listener.GetContextAsync();
if (context.Request.IsWebSocketRequest)
{
ProcessWebSocketRequest(context);
}
else
{
context.Response.StatusCode = 400;
context.Response.Close();
}
}
}
static async Task ProcessWebSocketRequest(HttpListenerContext context)
{
var webSocketContext = await context.AcceptWebSocketAsync(null);
var webSocket = webSocketContext.WebSocket;
var buffer = new byte[1024];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
var message = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received message: {message}");
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
}
WebSocket客戶端代碼示例:
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri("ws://localhost:8080/"), CancellationToken.None);
var input = Console.ReadLine();
var buffer = Encoding.UTF8.GetBytes(input);
await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
var receiveBuffer = new byte[1024];
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
var message = Encoding.UTF8.GetString(receiveBuffer, 0, result.Count);
Console.WriteLine($"Received message: {message}");
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closed by client", CancellationToken.None);
}
}
這是一個簡單的示例,演示了如何在C#中實現WebSocket服務器和客戶端之間的通信。您可以根據自己的需求和業務邏輯進一步擴展和修改這段代碼。