Windows Server 2019上C# WebSocket连接报503错误(预期101)求助
WebSocket连接抛出503错误(预期101)的解决方案
可能的原因及解决方法
1. 程序未以管理员权限运行
HttpListener需要绑定HTTP命名空间的权限,普通用户权限下无法完成端口监听,导致服务不可用返回503。
- 解决:右键点击程序执行文件/开发工具,选择以管理员身份运行。
- 若需普通用户也能运行,可通过命令行注册URL权限:
netsh http add urlacl url=http://127.0.0.1:8085/ user=你的用户名
2. 8085端口被其他进程占用
端口被占用会导致HttpListener无法正常监听,服务无法响应请求。
- 解决:打开命令提示符,执行以下命令查看占用端口的进程:
根据返回的PID,在任务管理器中结束对应进程,或修改服务端代码更换端口(如8086)。netstat -ano | findstr :8085
3. 服务端代码未循环处理请求
当前服务端代码仅处理一次请求,若首次请求未被正确处理或服务端已退出,后续连接会返回503。需修改代码实现循环监听:
HttpListener httpListener = new HttpListener(); httpListener.Prefixes.Add("http://127.0.0.1:8085/"); httpListener.Start(); Console.WriteLine("HttpListener started at 127.0.0.1/8085 successfully."); // 循环处理所有请求 while (true) { HttpListenerContext context = await httpListener.GetContextAsync(); if (context.Request.IsWebSocketRequest) { try { HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(subProtocol: null); WebSocket webSocket = webSocketContext.WebSocket; await webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Hello")), WebSocketMessageType.Text, true, CancellationToken.None); // 完成通信后关闭连接 await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "连接正常关闭", CancellationToken.None); } catch (Exception ex) { context.Response.StatusCode = 500; context.Response.Close(); Console.WriteLine($"WebSocket处理异常: {ex.Message}"); } } else { // 拒绝非WebSocket请求 context.Response.StatusCode = 400; context.Response.Close(); } }
4. Windows防火墙拦截端口
Windows Server默认防火墙规则可能拦截8085端口的入站连接,导致请求无法到达服务端。
- 解决:打开Windows Defender防火墙,添加入站规则允许8085端口的TCP连接;或临时关闭防火墙测试是否恢复正常。
内容的提问来源于stack exchange,提问作者Anurag Jain
相关产品推荐
相关产品推荐

