如何在ASP Net Core中的服务之间共享WebSocket

时间:2019-01-08 09:07:00

标签: c# asp.net-core websocket .net-core middleware

我正在使用中间件在.net核心上设置websocket(看起来像https://radu-matei.com/blog/aspnet-core-websockets-middleware/),但是我有一个问题 例如,我的客户端通过http协议与websocket进行通信,换句话说,websocket封装在http中,当我的客户端发送http请求时,它转到服务方法,最终使用websocket发送消息。 问题:是否可以在返回响应之前得到websocket的回复?

public async Task SendMessage(WebSocket socket, string response)
{
    if (socket.State != WebSocketState.Open)
        return;

    await socket.SendAsync(buffer: new ArraySegment<byte>(array: Encoding.UTF8.GetBytes(response),
            offset: 0,
            count: response.Length),
        messageType: WebSocketMessageType.Text,
        endOfMessage: true,
        cancellationToken: CancellationToken.None);

    await socket.ReceiveAsync() // When I finally receive some reply message, stop listening and return http response to my client
}

1 个答案:

答案 0 :(得分:0)

根据您所说的,我了解到您需要在多个服务之间共享websocket,每个服务都应使用它的合适方式。根据这种情况,建议的实现具有一个Middleware,其中包含需要插座。在决定由哪个服务进行写入和由哪个服务进行读取时,必须格外小心。websocket同时在reading-writing的上下文中是线程安全的,但在其他情况下则不是。(writing-writingreading-reading

启动

public void ConfigureServices(IServiceCollection colllection){
     collection.AddSingleton<Sender>();
     collection.AddSingleton<Receiver>();
 }
 public void Configure(IApplicationBuilder app)
 {
    app.UseWebsockets();
    app.UseMiddleware<DispatcherMiddleware>(); //receives socket here

 }

中间件

public class DispatcherMiddleware{
    private Sender sender;
    private Receiver receiver;
    private RequestDelegate next;
   public Dispatcher(RequestDelegate req,Sender _sender,Receiver _receiver)
   {
    this.sender=_sender;
    this.receiver=_receiver;
    this.next=req;
   }
    public async Task Invoke(HttpContext context){
        if(!context.WebSockets.IsWebSocketRequest){
            return;
        }
        await DispatchAsync(context.WebSockets);
    }
    public async Task DispatchAsync(WebsocketManager manager){
         WebSocket socket=await manager.AcceptWebSocketAsync();
         Task t1=Task.Run(async()=>await this.sender.SendAsync(socket));
         Task t2=Task.Run(async()=>await this.receiver.ReceiveAsync(socket));
         await Task.WhenAll(t1,t2);

    }
}

Websocket服务(示例)

public class Sender(){
    public async Task SendAsync(WebSocket ws){
        try{
            while(true){
               // ws.SendAsync()
            }
        }
        catch(Exception ex){

        }

    }
}
public class Receiver{
    public async Task ReceiveAsync(WebSocket ws){
        try
        {
            while(true){
                //ws.ReceiveAsync(buffer)
            }
        }
        catch (System.Exception)
        {

            throw;
        }

    }
}

修改
您不能在同一套接字上执行并发读取/写入操作。因此,如果您要使用同一套接字,则可以将其设置为thread-safe。由于操作是async,因此我建议使用SemaphoreSlim类。

以下是shared套接字的实现:

public class SafeSocket {
        private const int BUFFER_SIZE = 1024;
        private WebSocket socket { get; set; }
        private SemaphoreSlim @lock = new SemaphoreSlim(1);
        public SafeSocket(WebSocket socket) {
            this.socket = socket;
        }
        public async Task<byte[]> ReadAsync() {
            byte[] buffer = ArrayPool<byte>.Shared.Rent(BUFFER_SIZE);
            await @lock.WaitAsync();
            try {
                await this.socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                return buffer;
            } catch (Exception) {

                throw;
            } finally {
                @lock.Release();
            }
        }

    }
    public class DispatcherMiddleware {
        private  List<Sender> senders;
        private Receiver receiver;
        private RequestDelegate next;
        public DispatcherMiddleware(RequestDelegate req, List<Sender> _senders, Receiver _receiver) {
            this.senders = _senders;
            this.receiver = _receiver;
            this.next = req;
        }
        public async Task Invoke(HttpContext context) {
            if (!context.WebSockets.IsWebSocketRequest) {
                return;
            }
            await DispatchAsync(context.WebSockets);
        }
        public async Task DispatchAsync(WebSocketManager manager) {

            WebSocket socket = await manager.AcceptWebSocketAsync();
            SafeSocket commonSocket = new SafeSocket(socket);
            Task[] senderTasks = new Task[this.senders.Count];
            for (int senderIndex = 0; senderIndex < senderTasks.Length; senderIndex++) {
                int index = senderIndex;// careful at index ! , make copy and use it inside closure !
                senderTasks[senderIndex] = Task.Run(async () => {
                    await commonSocket.ReadAsync();
                });
            }
        }

请记住,不会保留消息顺序。相同的方法也可以应用于接收者。
所以最终您将得到N的发送者和K的接收者,即时间T

  1. 1发送者将写信
  2. 1收件人将阅读
  3. N-1发送者将等待lock
  4. K-1接收者将等待lock

所以最终在任何给定时间都只有2个操作。 我不知道那是否是您所需要的。