来一段.net 6 搭建websocket服务,并用控制器的方式创建连接,并附上客户端代码
时间: 2024-02-19 22:03:35 浏览: 91
简单实现了websocket功能:websocket客户端、winformsocket客户端
好的,以下是一个使用 ASP.NET Core 6 控制器创建 WebSocket 服务的示例,同时也包含了客户端代码:
在控制台应用程序或 ASP.NET Core Web 应用程序中,首先需要添加对 `Microsoft.AspNetCore.WebSockets` NuGet 包的引用。
在控制器中,需要注入 `IWebSocketFactory` 接口,并在 Action 中使用它来创建 WebSocket 连接。以下是示例代码:
```csharp
using System.Net.WebSockets;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace MyWebSocketApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class MyWebSocketController : ControllerBase
{
private readonly ILogger<MyWebSocketController> _logger;
private readonly IWebSocketFactory _webSocketFactory;
public MyWebSocketController(ILogger<MyWebSocketController> logger, IWebSocketFactory webSocketFactory)
{
_logger = logger;
_webSocketFactory = webSocketFactory;
}
[HttpGet("{id}")]
public async Task Get(string id)
{
if (!HttpContext.WebSockets.IsWebSocketRequest)
{
HttpContext.Response.StatusCode = 400;
return;
}
WebSocket webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
_logger.LogInformation($"WebSocket connection with ID {id} established");
await HandleWebSocketConnection(webSocket);
_logger.LogInformation($"WebSocket connection with ID {id} closed");
}
private async Task HandleWebSocketConnection(WebSocket webSocket)
{
// handle incoming WebSocket messages here
}
}
}
```
在客户端代码中,可以使用 `WebSocket` 类来连接 WebSocket 服务。以下是示例代码:
```csharp
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MyWebSocketClient
{
class Program
{
private static readonly Uri _uri = new Uri("ws://localhost:5000/MyWebSocket/123");
static async Task Main(string[] args)
{
using (ClientWebSocket webSocket = new ClientWebSocket())
{
await webSocket.ConnectAsync(_uri, CancellationToken.None);
// send a message to the server
string message = "Hello, server!";
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
await webSocket.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true, CancellationToken.None);
// receive incoming WebSocket messages here
byte[] buffer = new byte[1024];
while (webSocket.State == WebSocketState.Open)
{
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
string incomingMessage = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received message from server: {incomingMessage}");
}
}
}
}
}
```
当客户端连接到 `ws://localhost:5000/MyWebSocket/123` 时,将创建一个新的 WebSocket 连接,并在控制台中记录连接消息。在 `HandleWebSocketConnection` 方法中,可以处理从客户端发送的所有 WebSocket 消息。
这只是一个简单的示例,实际情况可能更复杂。但是,这应该足以让你开始构建自己的 ASP.NET Core 6 WebSocket 服务了。
阅读全文