首页 > 解决方案 > HttpListenerContext.AcceptWebSocketAsync 错误 1229

问题描述

我正在尝试将 WebSocket 添加到处理 HTTP 请求的现有代码中。不使用 IIS 或 ASP.NET,只使用带有 HttpListener 的 C# 代码。当客户端发送升级请求时,服务器炸弹:

System.Net.WebSockets.WebSocketException was unhandled by user code
  ErrorCode=1229
  HResult=-2147467259
  Message=An error occurred when sending the WebSocket HTTP upgrade response during the AcceptWebSocketAsync operation. The HRESULT returned is '1229'
  NativeErrorCode=1229
  Source=System
  StackTrace:
       at System.Net.WebSockets.WebSocketHelpers.<AcceptWebSocketAsyncCore>d__17.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at mycode.<mymethod>d__46.MoveNext() 
  InnerException: 

调用代码:

HttpListenerContext context = listener.GetContext();
if (context.Request.IsWebSocketRequest)
{
    HttpListenerWebSocketContext wsContext = await context.AcceptWebSocketAsync(null);

我发现整个 WebSockets 命名空间上的 MS 文档在没有代码示例的情况下毫无用处。我不知道它在这里试图告诉我什么(除了我没有处理异常这一明显事实 - 我想知道为什么首先会出现异常)。

这是 Windows 10,.NET 框架 4.5。我注意到文档中的一些地方说 WebSockets 仅适用于 Windows 8 和 2012,但我认为它也应该适用于 10。

标签: websocket

解决方案


必须转到 IIS 下的 Windows 功能(即使我没有使用 IIS),然后打开 WebSocket 协议。我不知道这是否是 Win10 默认关闭的,或者只是因为为我安装的图像 IT。


推荐阅读