在C#中,处理WebSocket连接通常需要使用System.Net.WebSockets
命名空间中的WebSocket
类。以下是一个简单的示例,展示了如何创建一个基本的WebSocket服务器来处理连接:
System.Net.WebSockets
命名空间。在.csproj
文件中添加以下引用:<PackageReference Include="System.Net.WebSockets" Version="4.5.3" />
using System;
using System.Net.WebSockets;
using System.Threading.Tasks;
public class WebSocketServer
{
private const string Uri = "ws://localhost:8080/websocket";
private readonly WebSocketServer _server;
public WebSocketServer()
{
_server = new WebSocketServer(Uri);
}
public async Task StartAsync()
{
_server.Start();
Console.WriteLine("WebSocket server started on {0}", Uri);
while (_server.State == WebSocketServerState.Running)
{
var result = await _server.AcceptWebSocketAsync();
HandleClientConnected(result.WebSocket);
}
}
private void HandleClientConnected(WebSocket webSocket)
{
Console.WriteLine("Client connected: {0}", webSocket.Id);
_ = webSocket.ReceiveAsync(new ArraySegment<byte>(new byte[1024 * 4]), CancellationToken.None)
.ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
{
var receivedData = t.Result.ToArray();
Console.WriteLine($"Received data: {System.Text.Encoding.UTF8.GetString(receivedData)}");
_ = webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Message received")), WebSocketMessageType.Text, true, CancellationToken.None)
.ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
{
Console.WriteLine("Message sent to client");
}
});
}
});
}
}
WebSocketServerState
枚举和一个WebSocketServer
类,如下所示:public enum WebSocketServerState
{
Stopped,
Running
}
public class WebSocketServer
{
private readonly Uri _uri;
private WebSocket _webSocket;
private WebSocketServerState _state;
public WebSocketServer(Uri uri)
{
_uri = uri;
_state = WebSocketServerState.Stopped;
}
public WebSocketServerState State
{
get => _state;
private set
{
_state = value;
Console.WriteLine($"WebSocket server state changed to: {_state}");
}
}
public async Task StartAsync()
{
State = WebSocketServerState.Running;
var listener = new HttpListener();
listener.Prefixes.Add(_uri);
listener.Start();
Console.WriteLine("WebSocket server started on {0}", _uri);
while (State == WebSocketServerState.Running)
{
var context = await listener.GetContextAsync();
if (context.Request.HttpMethod == "GET")
{
var request = new HttpWebSocketContext(context, _uri);
_webSocket = request.WebSocket;
HandleClientConnected(_webSocket);
}
}
}
public async Task AcceptWebSocketAsync()
{
return await _webSocket.AcceptWebSocketAsync();
}
}
Main
方法中启动WebSocket服务器:public static async Task Main(string[] args)
{
var server = new WebSocketServer();
await server.StartAsync();
}
现在,当客户端连接到WebSocket服务器时,服务器将接收到的消息原样发送回客户端。你可以根据需要扩展此示例以处理更复杂的场景,例如发送消息到特定客户端或广播消息给所有连接的客户端。