Created
April 8, 2024 13:41
-
-
Save glebov21/fe6e478980fd5e7864d16c37a34cf040 to your computer and use it in GitHub Desktop.
asp.net core websockets example via controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Authentication; | |
using Microsoft.AspNetCore.Authorization; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.AspNetCore.Mvc; | |
using System.Net.WebSockets; | |
namespace WebAPI.Controllers | |
{ | |
[Route("/ws")] | |
[ApiController] | |
public class WSController : ControllerBase | |
{ | |
[HttpGet] | |
[AllowAnonymous] | |
public async Task Get() | |
{ | |
if(HttpContext.WebSockets.IsWebSocketRequest) | |
{ | |
using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync(new WebSocketAcceptContext() | |
{ | |
DangerousEnableCompression = true, | |
}); | |
await Echo(webSocket); | |
} | |
else | |
{ | |
HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest; | |
} | |
} | |
private async Task Echo(WebSocket webSocket) | |
{ | |
var buffer = new byte[1024 * 4]; | |
WebSocketReceiveResult receiveResult; | |
while (true) | |
{ | |
//Wait request | |
receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); | |
if (receiveResult.CloseStatus.HasValue) | |
break; | |
//Echo | |
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, receiveResult.Count), | |
receiveResult.MessageType, | |
receiveResult.EndOfMessage, | |
CancellationToken.None); | |
} | |
await webSocket.CloseAsync(receiveResult.CloseStatus.Value, receiveResult.CloseStatusDescription, CancellationToken.None); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment