// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024, // AllowedOrigins = { "https://localhost:44333/" } }); app.Use(async(context, next) => { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { var users = context.RequestServices.GetService <IClientUsers>(); var user_name = context.Request.Query["user"]; var webSocket = await context.WebSockets.AcceptWebSocketAsync(); users.clients.Add(user_name, webSocket); var buffer = new ArraySegment <byte>(new byte[1024 * 4]); var result = await webSocket.ReceiveAsync(buffer, CancellationToken.None); while (!result.CloseStatus.HasValue) { var chartImps = context.RequestServices.GetServices <IChartEvent>(); var byteArrayContent = await buffer.ConvertToStreamAsync(result.Count); var user_req = chatMessageRequest.Parser.ParseFrom(byteArrayContent); var msg_type = (EMessageType)user_req.MsgType; var instance = chartImps.FirstOrDefault(s => s.MessageType == msg_type); if (instance != null) { await instance.MessageSend(user_req); } result = await webSocket.ReceiveAsync(buffer, CancellationToken.None); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); } else { context.Response.StatusCode = 400; } } else { await next(); } }); }
public async Task Send(string strByteArray) { var myByteArray = Convert.FromBase64String(strByteArray); var buffer = new ArraySegment <byte>(myByteArray); var byteArrayContent = await buffer.ConvertToStreamAsync(buffer.Count); var user_req = chatMessageRequest.Parser.ParseFrom(byteArrayContent); var instance = _chartEvents.FirstOrDefault(w => w.MessageType == (EMessageType)user_req.MsgType); await instance.MessageSend(Clients, user_req); }