在C#中,使用WebSocketServer可以获取多种类型的数据。以下是一些常见的数据类型:
要使用C# WebSocketServer获取这些数据,你需要使用System.Net.WebSockets
命名空间中的WebSocket
类。以下是一个简单的示例,展示了如何使用C# WebSocketServer接收字符串数据:
using System;
using System.Net.WebSockets;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
public class WebSocketHandler
{
private readonly WebSocket _webSocket;
public WebSocketHandler(WebSocket webSocket)
{
_webSocket = webSocket;
}
public async Task OnConnectedAsync(HttpContext context)
{
var buffer = new byte[1024 * 4];
WebSocketReceiveResult result;
do
{
result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
var receivedData = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received data: {receivedData}");
}
while (!result.CloseStatus.HasValue);
}
public async Task OnDisconnectedAsync(WebSocket webSocket, WebSocketCloseStatus closeStatus, string closeStatusDescription)
{
Console.WriteLine($"WebSocket disconnected: {closeStatusDescription}");
}
}
在这个示例中,我们创建了一个WebSocketHandler
类,它实现了OnConnectedAsync
和OnDisconnectedAsync
方法。OnConnectedAsync
方法用于处理WebSocket连接建立时的数据接收,而OnDisconnectedAsync
方法用于处理WebSocket连接断开时的操作。