使用的WebSockets与ASP.NET的Web API [英] Using WebSockets with ASP.NET Web API

查看:2541
本文介绍了使用的WebSockets与ASP.NET的Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是在ASP.NET Web API应用程序使用原始的WebSockets的preferred方法?

What is the preferred method for using raw websockets in an ASP.NET Web API application?

我们想使用的WebSockets的一对夫妇我们我们的ASP.NET Web API应用程序接口组成。我有困难的时候决定如何应该这样做,因为好像在网上几个相互冲突的和/或过时的实现为.NET。

We'd like to use binary WebSockets on a couple of our interfaces of our ASP.NET Web API application. I'm having a difficult time determining how this should be done as there seems to be several conflicting and/or out-dated implementations online for .NET.

有这似乎是ASP.NET这样的<一个例子href=\"http://www.$c$cguru.com/csharp/csharp/programming-html5-web-sockets-in-asp.net-4.5.htm\">one,但我的认为的必须有在Web API框架内使用WebSockets的手段。当我知道你可以的WebAPI中使用Signalr。

There are examples which appear to be ASP.NET like this one, but I think there must be a means to use websockets within the Web API framework. As I know you can use Signalr within WebAPI.

我的认为的使用Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler会的工作,但我不知道如何将WebSocketHandler链接到控制器...

I thought using Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler would work, but I'm not sure how to link the WebSocketHandler to the Controller...

class MyServiceController : ApiController
{
    [HttpGet]
    public HttpResponseMessage SwitchProtocols (string param)
    {
        HttpContext currentContext = HttpContext.Current;
        if (currentContext.IsWebSocketRequest || 
            currentContext.IsWebSocketRequestUpgrading)
        {
            // several out-dated(?) examples would 
            // use 'new MySocketHandler' for ???
            var unknown = new ????
            currentContext.AcceptWebSocketRequest(unknown); 
            return Request.CreateResponse(HttpStatusCode.SwitchingProtocols);
        }   
    }
}

class MySocketHandler : WebSocketHandler
{
    public MySocketHandler(): base(2048){}

    ...
}

不幸的是,AcceptWebSocketRequest不再接受WebSocketHandler,而不是它的新的签名是...

Unfortunately, AcceptWebSocketRequest no longer accepts a WebSocketHandler, instead its new signature is...

public void AcceptWebSocketRequest(Func<AspNetWebSocketContext, Task> userFunc)

有没有人有一个链接或实施即达最新的?

Does anyone have a link or a quick sample implementing raw websockets in ASP.NET Web API application that is up-to-date?

推荐答案

更新:由我和同事多一点的研究后,我们得出的结论是,WebSocketHandler类不会出现意SignalR的内部过程之外使用。由于没有明显的方法来利用WebSocketHandler从SignalR隔离。这是不幸的,因为我觉得它的接口略多层次的高比的System.Web / System.Net接口。此外,以下描述的方法使用的HttpContext的我相信的,应该避免。

UPDATE: After a bit more research by myself and a coworker, we came to the conclusion that the WebSocketHandler class does not appear to be intended to be used outside of the internal processes of SignalR. As there is no obvious means to leverage WebSocketHandler isolated from SignalR. This is unfortunate as I find its interfaces slightly more high-level than the System.Web/System.Net interfaces. Moreover, the method described below makes use of HttpContext which I believe should be avoided.

因此​​,我们计划采取类似于Mrchief所示的一种方法,但更多的是位Web API的味道。像这样...(注:我们的插座是只写的,但我发现您你想WebSocket.State得到正确更新必须执行读操作

As such we plan to take an approach similar to the one shown by Mrchief, but with a bit more Web API flavor. Like this...(NOTE: our socket is write-only, but I discovered you MUST perform read operations of you want WebSocket.State to get updated properly.

class MyServiceController : ApiController
{
    public HttpResponseMessage Get (string param)
    {
        HttpContext currentContext = HttpContext.Current;
        if (currentContext.IsWebSocketRequest || 
            currentContext.IsWebSocketRequestUpgrading)
        {
            currentContext.AcceptWebSocketRequest(ProcessWebsocketSession); 
            return Request.CreateResponse(HttpStatusCode.SwitchingProtocols);
        }   
    }

    private async Task ProcessWebsocketSession(AspNetWebSocketContext context)
    {
        var ws = context.WebSocket;

        new Task(() =>
        {
            var inputSegment = new ArraySegment<byte>(new byte[1024]);

            while (true)
            {
                // MUST read if we want the state to get updated...
                var result = await ws.ReceiveAsync(inputSegment, CancellationToken.None);

                if (ws.State != WebSocketState.Open)
                {
                    break;
                }
            }
        }).Start();

        while (true)
        {
            if (ws.State != WebSocketState.Open)
            {
                break;
            }
            else
            {
                byte[] binaryData = { 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe };
                var segment = new ArraySegment<byte>(binaryData);
                await ws.SendAsync(segment, WebSocketMessageType.Binary, 
                    true, CancellationToken.None);
            }
        }
    }
}

请注意:很明显的错误检查和的CancellationToken的正确用法是作为练习留给读者。

NOTE: Obviously error checking and proper usage of a CancellationToken is left as an exercise for the reader.

这篇关于使用的WebSockets与ASP.NET的Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆