将websockets接口添加到独立进程

时间:2015-11-16 11:20:46

标签: c# asp.net multithreading backgroundworker asp.net-core

如果我有一个连续运行的独立进程,是否有一个很好的方法可以添加一个asp.net websocket接口,以便我可以发送消息与这个进程交互并广播状态更新?消息可能非常大和/或频繁。

此过程不需要安排,因为它会在应用程序启动后立即运行。

我问,因为最初我以为我会运行一个在启动时创建一个线程的asp.net应用程序(在Startup.Configure中我想?)但是我一直在读asp.net isn'设计用于具有后台线程。使用Windows服务,但我正在为Linux和OSX开发。

这就是我想要实现的目标:

public class Startup
{
    BackgroundServer server;

    public void Configure(IApplicationBuilder app)
    {
        // start server in another thread
        Task task = new Task( () => server.run(); );
        task.Start();

        app.Map("/ws", webSocketsApp =>
        {
            //  need this to enable websocket middleware!
            webSocketsApp.UseWebSockets(new WebSocketOptions() {ReplaceFeature = true, });

            webSocketsApp.Use(async (context, next) =>
            {
                if (context.WebSockets.IsWebSocketRequest)
                {
                    var webSocket = await context.WebSockets.AcceptWebSocketAsync();
                    await Task.WhenAll([]{ProcessMessages(webSocket), ProcessSends(websocket)});
                    return;
                }
                await next();
            });
        });
    }

    private async Task ProcessMessages(WebSocket webSocket)
    {

        byte[] buffer = new byte[1024 * 4];
        var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        while (!result.CloseStatus.HasValue)
        {
            await server.sendMessage(websocket, message);
        }
        await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
    }

    private async Task ProcessSends(WebSocket webSocket)
    {
        while (!webSocket.isStateTerminal)
        {
            var message = await server.getMessage();
            await webSocket.SendAsync(new ArraySegment<byte>(message), Text, true, CancellationToken.None);
        }
        await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
    }

}

0 个答案:

没有答案