I have a .NET server accepting WebSocket connections and responding with whatever messages are sent. When I connect from Safari everything works as expected until I close the WebSocket and receive the following error
WebSocket connection to 'ws://localhost:8080' failed: The operation couldn’t be completed. Socket is not connected
The socket was connected and as I mentioned I was able to send and receive messages before attempting to close it. It’s readyState is OPEN before closing as well.
This is the .NET code I have
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Enable WebSocket support
app.UseWebSockets();
app.Urls.Add("http://localhost:8080");
app.Map("/", async context =>
{
if (context.WebSockets.IsWebSocketRequest)
{
var webSocket = await context.WebSockets.AcceptWebSocketAsync();
await Echo(webSocket);
}
else
{
context.Response.StatusCode = 400;
}
});
app.Run();
static async Task Echo(System.Net.WebSockets.WebSocket webSocket)
{
var buffer = new byte[1024 * 4];
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
And this is the javascript code I have in the browser
ws = new WebSocket('ws://localhost:8080')
ws.send('abc')
ws.close()
Jason Graham is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0