【发布时间】:2014-12-31 21:22:30
【问题描述】:
我们有一个有效的 ASP.NET Web API REST 服务,它在使用 HttpContext.AcceptWebSocketResponse(..) 的控制器方法之一上使用 WebSockets。
代码看起来像这样的套接字处理程序......
public async Task SocketHandler(AspNetWebSocketContext context)
{
_webSocket = context.WebSocket;
...
while(!cts.IsCancellationRequested)
{
WebSocketReceiveResult result = _webSocket.ReceiveAsync(inputSegment, cts.Token).Result;
WebSocketState currentSocketState = _webSocket.State;
if (result.MessageType == WebSocketMessageType.Close ||
currentSocketState == WebSocketState.CloseReceived)
{
// Should I use .CloseAysnc() or .CloseOutputAsync()?
_webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "client requested", cts.Token).Wait();
}
if (currentSocketState == WebSocketState.Open)
{
...
}
}
}
.CloseAsync() 和 CloseOutputAysnc() 有什么区别?我都试过了,它们似乎都工作得很好,但肯定有一些区别。它们在 MSDN 上都有非常相似的描述...
System.Net.WebSockets.CloseAsync -- 使用 WebSocket 协议规范第 7 节中定义的关闭握手作为异步操作关闭 WebSocket 连接。
System.Net.WebSockets.CloseOutputAsync -- 启动或完成 WebSocket 协议规范第 7 节中定义的关闭握手。
【问题讨论】:
标签: c# .net asp.net-web-api websocket