/// <summary>
        /// 返回信息到用户
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="userWebSocket"></param>
        /// <param name="wsFactory"></param>
        /// <returns></returns>
        public async Task BroadcastOthers(byte[] buffer, string username, ICustomWebSocketFactory wsFactory)
        {
            var others = wsFactory.Others(username);

            foreach (var uws in others)
            {
                //string msg = Encoding.UTF8.GetString(buffer);
                //String JSON = msg.Replace("\u0000", "");
                //CustomWebSocketMessage message = JSON.ConvertToObject<CustomWebSocketMessage>();

                //if (message.Type == WSMessageType.发送)
                //{

                Helperlog4.Info("返回信息到用户" + uws.ConvertToJson() + "&&&&" + Encoding.UTF8.GetString(buffer));
                //string serialisedMessage = JsonConvert.SerializeObject(message);
                //buffer = Encoding.UTF8.GetBytes(serialisedMessage);
                await uws.WebSocket.SendAsync(new ArraySegment <byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);

                //}
            }

            //var others = wsFactory.Client(userWebSocket.Username);

            //await others.WebSocket.SendAsync(new ArraySegment<byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);
        }
Example #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAutomaticPostingFactory apFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            //app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });

            var webSocketOptions = new WebSocketOptions()
            {
                KeepAliveInterval = TimeSpan.FromSeconds(120),
                ReceiveBufferSize = 4 * 1024
            };

            app.UseWebSockets(webSocketOptions);
            app.UseCustomWebSocketManager();
            //app.AutomaticPostingApp();
            string Text = HelperAspNet.Http.HttpGet("http://172.16.1.34:7777/api/GetAutomaticPosting/GetAutomaticPostingAPI");

            List <AutomaticPosting> AutomaticPostingList = new List <AutomaticPosting>();

            AutomaticPostingList = Text.ConvertToList <AutomaticPosting>();

            foreach (AutomaticPosting item in AutomaticPostingList)
            {
                Helperlog4.Info("取得未过账数据" + item.ConvertToJson());
                apFactory.AutomaticPostingAdd(item);
            }
            Helperlog4.Info("取得未过账数据" + AutomaticPostingList.ConvertToJson());

            if (AutomaticPostingList.Count == 0)
            {
                AutomaticPosting AutomaticPostings = new AutomaticPosting();

                AutomaticPostings.id         = 0;
                AutomaticPostings.in_time    = null;
                AutomaticPostings.item_num   = null;
                AutomaticPostings.JobNumber  = null;
                AutomaticPostings.state      = 0;
                AutomaticPostings.Warehouse_ = null;
                apFactory.AutomaticPostingAdd(AutomaticPostings);
            }
        }
        /// <summary>
        /// 侦听
        /// </summary>
        /// <param name="context"></param>
        /// <param name="userWebSocket"></param>
        /// <param name="wsFactory"></param>
        /// <param name="wsmHandler"></param>
        /// <returns></returns>
        private async Task Listen(HttpContext context, CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler, IAutomaticPostingFactory apFactory)
        {
            WebSocket webSocket           = userWebSocket.WebSocket;
            var       buffer              = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                await wsmHandler.HandleMessage(result, buffer, userWebSocket, wsFactory, apFactory);

                buffer = new byte[1024 * 4];
                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }
            wsFactory.Remove(userWebSocket.Username);
            Helperlog4.Info("删除连接值" + userWebSocket.Username);
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
        /// <summary>
        /// 返回信息到某类型用户
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="usertype"></param>
        /// <param name="wsFactory"></param>
        /// <returns></returns>
        public async Task BroadcastUserTypeOthers(byte[] buffer, UserType usertype, ICustomWebSocketFactory wsFactory)
        {
            List <CustomWebSocket> others = wsFactory.All().Where(a => a.UserType == UserType.过账客户端).ToList();

            Helperlog4.Info("返回信息到某类型用户,共找到下列用户:" + others.ConvertToJson());
            foreach (CustomWebSocket uws in others)
            {
                //string msg = Encoding.UTF8.GetString(buffer);
                //String JSON = msg.Replace("\u0000", "");
                //CustomWebSocketMessage message = JSON.ConvertToObject<CustomWebSocketMessage>();

                //if (message.Type == WSMessageType.发送)
                Helperlog4.Info("返回信息到过账客户端:" + uws.Username + " 返回的数据为:" + uws.ConvertToJson() + "&&&&" + Encoding.UTF8.GetString(buffer));
                //string serialisedMessage = JsonConvert.SerializeObject(message);
                //buffer = Encoding.UTF8.GetBytes(serialisedMessage);
                await uws.WebSocket.SendAsync(new ArraySegment <byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);

                //}
            }

            //var others = wsFactory.Client(userWebSocket.Username);

            //await others.WebSocket.SendAsync(new ArraySegment<byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);
        }
        /// <summary>
        /// 处理消息
        /// </summary>
        /// <param name="result"></param>
        /// <param name="buffer"></param>
        /// <param name="userWebSocket"></param>
        /// <param name="wsFactory"></param>
        /// <returns></returns>
        public async Task HandleMessage(WebSocketReceiveResult result, byte[] buffer, CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory, IAutomaticPostingFactory apFactory)
        {
            string msg = Encoding.UTF8.GetString(buffer);

            try
            {
                //var message = JsonConvert.DeserializeObject<CustomWebSocketMessage>(msg);
                String JSON = msg.Replace("\0", "");
                CustomWebSocketMessage message = JSON.ConvertToObject <CustomWebSocketMessage>();
                if (message.Type == EnumModel.WSMessageType.发送 && message.UserType == UserType.挂工艺数据)
                {
                    message.Text = HelperAspNet.Http.HttpGet("http://172.16.14.250:7031/MesStationMasterMbjGetApi?StationNo=" + message.Username);
                    string serialisedMessage = JsonConvert.SerializeObject(message);
                    Helperlog4.Info("返回吊挂工艺数据" + serialisedMessage);
                    await BroadcastOthers(Encoding.UTF8.GetBytes(serialisedMessage), message.Username, wsFactory);
                }
                else if (message.Type == EnumModel.WSMessageType.发送 && message.UserType == UserType.挂模板数据)
                {
                    message.Text = HelperAspNet.Http.HttpGet("http://172.16.14.250:7030/MesStationMasterAppGetApi?StationNo=" + message.Username);
                    string serialisedMessage = JsonConvert.SerializeObject(message);
                    Helperlog4.Info("返回吊挂吊挂模板数据" + serialisedMessage);
                    await BroadcastOthers(Encoding.UTF8.GetBytes(serialisedMessage), message.Username, wsFactory);
                }
                else if (message.Type == EnumModel.WSMessageType.发送 && message.UserType == UserType.过账客户端)
                {
                    message.Text = apFactory.AutomaticPostingAll().ConvertToJson();
                    string serialisedMessage = JsonConvert.SerializeObject(message);
                    Helperlog4.Info("发送过账客户端" + serialisedMessage);
                    await BroadcastOthers(Encoding.UTF8.GetBytes(serialisedMessage), message.Username, wsFactory);

                    //await BroadcastUserTypeOthers(Encoding.UTF8.GetBytes(serialisedMessage), UserType.过账客户端, wsFactory);
                }
                else if (message.Type == EnumModel.WSMessageType.发送 && message.UserType == UserType.过账数据端)
                {
                    if (message.Text == "Update")
                    {
                        message.Text = HelperAspNet.Http.HttpGet("http://172.16.1.34:7777/api/GetAutomaticPosting/GetAutomaticPostingAPI");

                        List <AutomaticPosting> AutomaticPostingList = new List <AutomaticPosting>();
                        AutomaticPostingList = message.Text.ConvertToList <AutomaticPosting>();
                        foreach (AutomaticPosting item in AutomaticPostingList)
                        {
                            apFactory.AutomaticPostingAdd(item);
                        }
                        Helperlog4.Info("添加过账数据端" + AutomaticPostingList.ConvertToJson());
                    }
                    else if (message.Text == "Get")
                    {
                        List <AutomaticPosting> AutomaticPostingList = new List <AutomaticPosting>();
                        AutomaticPostingList = apFactory.AutomaticPostingAll();
                        message.Text         = AutomaticPostingList.ConvertToJson();
                        string serialisedMessage = JsonConvert.SerializeObject(message);
                        await BroadcastUserTypeOthers(Encoding.UTF8.GetBytes(serialisedMessage), message.UserType, wsFactory);

                        Helperlog4.Info("过账数据端Get" + serialisedMessage);
                    }
                }
                else if (message.Type == EnumModel.WSMessageType.发送 && message.UserType == UserType.过账数据添加端)
                {
                    List <AutomaticPosting> AutomaticPostingList = new List <AutomaticPosting>();
                    AutomaticPostingList = message.Text.ConvertToList <AutomaticPosting>();
                    foreach (AutomaticPosting item in AutomaticPostingList)
                    {
                        apFactory.AutomaticPostingAdd(item);
                    }
                    string serialisedMessage = JsonConvert.SerializeObject(message);
                    Helperlog4.Info("过账数据添加端" + serialisedMessage);
                    await BroadcastUserTypeOthers(Encoding.UTF8.GetBytes(serialisedMessage), UserType.过账客户端, wsFactory);
                }
                else if (message.Type == EnumModel.WSMessageType.发送 && message.UserType == UserType.过账数据删除端)
                {
                    List <AutomaticPosting> AutomaticPostingList = new List <AutomaticPosting>();
                    AutomaticPostingList = message.Text.ConvertToList <AutomaticPosting>();
                    foreach (AutomaticPosting item in AutomaticPostingList)
                    {
                        apFactory.AutomaticPostingRemove(item);
                        Helperlog4.Info("过账数据删除端" + message.Username + " 删除服务器内存数据" + JsonConvert.SerializeObject(item));
                    }
                    string serialisedMessage = JsonConvert.SerializeObject(message);
                    await BroadcastUserTypeOthers(Encoding.UTF8.GetBytes(serialisedMessage), UserType.过账客户端, wsFactory);

                    Helperlog4.Info("过账数据删除端" + message.Username + "给过账客户端返回数据完成!" + serialisedMessage);
                }
                else if (message.Type == WSMessageType.登陆)
                {
                    await userWebSocket.WebSocket.SendAsync(new ArraySegment <byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
                }
                else if (message.Type == WSMessageType.重连)
                {
                    //    string serialisedMessage = JsonConvert.SerializeObject(message);
                    //    await BroadcastOthers(Encoding.UTF8.GetBytes(serialisedMessage), message.Username, wsFactory);
                }


                //if (message.Type == WSMessageType.发送 || message.Type == WSMessageType.重连)
                //{
                //    string serialisedMessage = JsonConvert.SerializeObject(message);
                //    await BroadcastOthers(Encoding.UTF8.GetBytes(serialisedMessage), message.Username, wsFactory);
                //}
            }
            catch (Exception e)
            {
                await userWebSocket.WebSocket.SendAsync(new ArraySegment <byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
            }
        }
        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="context"></param>
        /// <param name="wsFactory"></param>
        /// <param name="wsmHandler"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler, IAutomaticPostingFactory apFactory)
        {
            if (context.Request.Path == "/MesServiceStation")
            {
                Helperlog4.Info("新连接完成" + context.Request.Path.ToString());
                if (context.WebSockets.IsWebSocketRequest)
                {
                    System.Security.Principal.WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
                    string usesid           = currentUser.User.ToString();
                    string customwebsocketS = context.Request.Query["username"];
                    //string username = usesid + "------Name";
                    if (!string.IsNullOrEmpty(customwebsocketS))
                    {
                        CustomWebSocket customwebsocket = customwebsocketS.ConvertToObject <CustomWebSocket>();
                        WebSocket       webSocket       = await context.WebSockets.AcceptWebSocketAsync();

                        List <CustomWebSocket> CustomWebSocketList = new List <CustomWebSocket>();
                        CustomWebSocketList = wsFactory.Others(customwebsocket.Username);
                        if (CustomWebSocketList.Count > 0)
                        {
                            CustomWebSocket userWebSocket1 = new CustomWebSocket();
                            userWebSocket1 = CustomWebSocketList[0];
                            wsFactory.Remove(userWebSocket1.Username);
                            CustomWebSocket userWebSocket = new CustomWebSocket()
                            {
                                WebSocket = webSocket,
                                Username  = userWebSocket1.Username,
                                UseSid    = usesid,
                                Url       = context.Request.GetDisplayUrl(),
                                UserType  = userWebSocket1.UserType
                            };
                            wsFactory.Add(userWebSocket);
                            //await Heartbeat(wsFactory, wsmHandler);
                            Helperlog4.Info("重新连接返回值" + userWebSocket.ConvertToJson());
                            await wsmHandler.SendInitialMessages(userWebSocket);
                            await Listen(context, userWebSocket, wsFactory, wsmHandler, apFactory);
                        }
                        else
                        {
                            CustomWebSocket userWebSocket = new CustomWebSocket()
                            {
                                WebSocket = webSocket,
                                Username  = customwebsocket.Username,
                                UseSid    = usesid,
                                Url       = context.Request.GetDisplayUrl(),
                                UserType  = customwebsocket.UserType
                            };
                            wsFactory.Add(userWebSocket);

                            Helperlog4.Info("新连接返回值" + userWebSocket.ConvertToJson());
                            //await Heartbeat(wsFactory, wsmHandler);
                            await wsmHandler.SendInitialMessages(userWebSocket);
                            await Listen(context, userWebSocket, wsFactory, wsmHandler, apFactory);
                        }
                    }
                }
                else
                {
                    context.Response.StatusCode = 400;
                }
            }
            await _next(context);
        }