尝试使用JavScript客户端和ASP.NET服务器实现基本WebSockets通道。客户端代码:
function Connect()
{
var ws = new WebSocket("ws://" + window.location.host + "/callback.aspx");
ws.onmessage = function (a) { alert("Message"); };
ws.onopen = function (a) { alert("Open"); };
ws.onerror = function (a) { alert("Error"); };
}
Callback.aspx是一个基本的ASP.NET网页,它是:
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.IsWebSocketRequest)
{
HttpContext.Current.AcceptWebSocketRequest(SocketProc);
}
}
private static async Task SocketProc(AspNetWebSocketContext a)
{
try
{
ArraySegment<byte> Buffer = new ArraySegment<byte>(new Byte[1024]);
while (true)
{
WebSocketReceiveResult res = await a.WebSocket.ReceiveAsync(Buffer, CancellationToken.None);
if (a.WebSocket.State != WebSocketState.Open)
return;
}
}
catch (Exception exc)
{
Debug.WriteLine(exc);
}
}
当我尝试从客户端连接时,调用Page_Load
,然后调用SocketProc
,然后ReceiveAsync
立即抛出以下异常:
System.Net.WebSockets.WebSocketException (0x800703E3): The I/O operation has been aborted because of either a thread exit or an application request
at System.Web.WebSockets.WebSocketPipe.<>c__DisplayClass9_0.<ReadFragmentAsync>b__0(Int32 hrError, Int32 cbIO, Boolean fUtf8Encoded, Boolean fFinalFragment, Boolean fClose)
--- 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.Web.WebSockets.AspNetWebSocket.<DoWork>d__45`1.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.Web.WebSockets.AspNetWebSocket.<>c__DisplayClass36_0.<<ReceiveAsyncImpl>b__0>d.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 CleanProxy.callback.<SocketProc>d__2.MoveNext() in C:\dev\CleanModel\CleanProxy\callback.aspx.cs:line 37
在客户端上,OnOpen触发,然后是OnError。
如果我在ReceiveAsync
附近立即捕获异常,则WebSocket对象将关闭。
我在这里缺少什么?在IIS Express和IIS中的Windows Server 2016上进行测试。
编辑:我一直在测试内置的IE,但我现在尝试使用Chrome并遇到了不同的错误。这一次,没有异常,ReceiveAsync
返回MessageType = Close,CloseStatus = ProtocolError的对象。在客户端上,Chrome控制台出现错误:
WebSocket connection to 'ws://localhost:53329/callback.aspx' failed: Invalid frame header
EDIT2:它以某种方式使用HTTP处理程序而不是ASPX页面。辣妈。没有要求使用经典的ASP.NET,所以现在这样做,但问题可能仍未解决。