/// <summary>
        /// 全部广播
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="userWebSocket"></param>
        /// <param name="wsFactory"></param>
        /// <returns></returns>
        public async Task BroadcastAll(byte[] buffer, CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory)
        {
            var all = wsFactory.All();

            foreach (var uws in all)
            {
                await uws.WebSocket.SendAsync(new ArraySegment <byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }
        /// <summary>
        /// 心跳类
        /// </summary>
        public async Task Invoke(string Username, ICustomWebSocketFactory wsFactory, ICustomWebSocketMessageHandler wsmHandler)
        {
            while (true)
            {
                try
                {
                    System.Threading.Thread.Sleep(1000);

                    List <CustomWebSocket> CustomWebSocketList = new List <CustomWebSocket>();
                    CustomWebSocketList = wsFactory.Others(Username);

                    foreach (CustomWebSocket item in CustomWebSocketList)
                    {
                        if (item.WebSocket.State == WebSocketState.Aborted || item.WebSocket.State == WebSocketState.Closed)
                        {
                            wsFactory.Remove(item.Username);
                            ClientWebSocket _webSocket    = new ClientWebSocket();
                            CustomWebSocket userWebSocket = new CustomWebSocket()
                            {
                                WebSocket = _webSocket,
                                Username  = item.Username,
                                UseSid    = item.UseSid,
                                Url       = item.Url
                            };
                            wsFactory.Add(userWebSocket);
                            await wsmHandler.SendInitialMessages(userWebSocket);

                            //await Listen(context, userWebSocket, wsFactory, wsmHandler);
                        }
                    }
                }
                catch (WebSocketException e)
                {
                    // 产生 10035 == WSAEWOULDBLOCK 错误,说明被阻止了,但是还是连接的
                    //if (e.NativeErrorCode.Equals(10035))
                    //{
                    //    return true;
                    //}
                    //else
                    //{
                    //    return false;
                    //}
                }
                finally
                {
                    //socket.Blocking = blockingState;    // 恢复状态
                }
            }
        }
        /// <summary>
        /// 链接webSocket
        /// </summary>
        /// <param name="userWebSocket"></param>
        /// <returns></returns>
        public async Task SendInitialMessages(CustomWebSocket userWebSocket)
        {
            WebSocket webSocket = userWebSocket.WebSocket;
            var       msg       = new CustomWebSocketMessage
            {
                MessagDateTime = DateTime.Now,
                Type           = WSMessageType.登陆,
                Text           = "登录成功!",
                Username       = "******",
                Url            = ""
            };

            string serialisedMessage = JsonConvert.SerializeObject(msg);

            byte[] bytes = Encoding.UTF8.GetBytes(serialisedMessage);
            await webSocket.SendAsync(new ArraySegment <byte>(bytes, 0, bytes.Length), WebSocketMessageType.Text, true, CancellationToken.None);
        }
        /// <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="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);
            }
        }
Beispiel #6
0
 /// <summary>
 /// 添加链接到List
 /// </summary>
 /// <param name="uws"></param>
 public void Add(CustomWebSocket uws)
 {
     List.Add(uws);
 }
        /// <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);
        }