因为主要做CS开发,所以之前没怎么涉及WebSocket的使用。前面有个项目,想着前端能不能直接跟我这边交互,所以研究了一下.NET的WebSocket的使用。
客户端连接
客户端的连接相对比较简单,可以直接使用ClientWebSocket即可。
示例代码:
using System.Net.WebSockets;
using System.Threading;
using System;
using System.Text;
using var cws = new ClientWebSocket();
// 设置每隔 5 秒发送一个 Ping 请求
cws.Options.KeepAliveInterval = TimeSpan.FromSeconds(5);
// 如果 1 秒内请求的服务端没有响应,则终止连接
cws.Options.KeepAliveTimeout = TimeSpan.FromSeconds(1);
Uri serverUri = new Uri("ws://echo.websocket.org");
var cancellationToken = new CancellationToken();
// 连接 WebSocket 服务器
await cws.ConnectAsync(serverUri, cancellationToken);
await cws.SendAsync(Encoding.Default.GetBytes( "Hello, World!"), WebSocketMessageType.Text,true, new CancellationToken());
var buffer = new byte[1024];
await cws.ReceiveAsync(buffer, new CancellationToken());
Console.WriteLine(Encoding.Default.GetString(buffer));
Console.ReadLine();
服务端的监听
服务端的监听需要用到HttpListenerWebSocketContext,相比TCP和HTTP的监听会稍微复杂一点点。但其实也还行。
示例代码:
using System;
using System.Net;
using System.Net.Http.Headers;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
public class SimpleWebSocketServer
{
private HttpListener _listener;
public async Task StartAsync(string url)
{
_listener = new HttpListener();
_listener.Prefixes.Add(url);
_listener.Start();
Console.WriteLine($"Listening on {url}");
while (true)
{
var context = await _listener.GetContextAsync();
if (context.Request.IsWebSocketRequest)
{
ProcessWebSocketRequest(context);
}
else
{
// 处理非WebSocket请求
HandleHttpRequest(context);
}
}
}
private void ProcessWebSocketRequest(HttpListenerContext context)
{
var webSocketContext = context.AcceptWebSocketAsync(null).Result;
HandleWebSocketConnection(webSocketContext);
}
private async Task HandleWebSocketConnection(HttpListenerWebSocketContext webSocketContext)
{
var webSocket = webSocketContext.WebSocket;
var buffer = new byte[1024];
WebSocketReceiveResult result;
do
{
result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
// Echo the message back to the client
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
} while (!result.CloseStatus.HasValue);
webSocket.Dispose();
}
private void HandleHttpRequest(HttpListenerContext context)
{
// 处理普通的HTTP请求
context.Response.StatusCode = 200;
context.Response.Close();
}
}
标签:WebSocket,C#,System,关于,context,new,var,using
From: https://www.cnblogs.com/wzwyc/p/18494576