示例#1
0
        /// <summary>
        /// 发送新订单任务提醒
        /// </summary>
        /// <param name="id">商户id</param>
        /// <param name="code">订单编号</param>
        public async Task OrderNotifyAsync(int id, string code, int state)
        {
            var data   = code + "|" + state;
            var buffer = System.Text.Encoding.Default.GetBytes(data);

            // 发送客户端消息通知
            if (ClientSocketDictionary.ContainsKey(id))
            {
                // 客户端信息另外处理
                var dataClient   = code;
                var bufferClient = System.Text.Encoding.Default.GetBytes(dataClient);
                var result       = await OrderNotifyAsync(ClientSocketDictionary[id], bufferClient);

                if (!result)
                {
                    ClientSocketDictionary.Remove(id);
                }
                else
                {
                    // 如果客户端已经处理了通知,则不再发给网站处理
                    return;
                }
            }
            // 发送网站端消息通知
            if (SocketDictionary.ContainsKey(id))
            {
                var result = await OrderNotifyAsync(SocketDictionary[id], buffer);

                if (!result)
                {
                    SocketDictionary.Remove(id);
                }
            }
        }
示例#2
0
文件: Program.cs 项目: FH-VMS/FycnApi
        private static void TimeOut(object source, ElapsedEventArgs e)
        {
            AsyncSocketUserToken[] userTokenArray = null;
            AsyncSocketSvr.AsyncSocketUserTokenList.CopyList(ref userTokenArray);
            for (int i = 0; i < userTokenArray.Length; i++)
            {
                //Program.Logger.InfoFormat("clear machine id is {0}", userTokenArray[i].MachineId);

                if (MachineHelper.IsOnline(userTokenArray[i].MachineId) && userTokenArray[i].ConnectSocket.RemoteEndPoint.ToString() == MachineHelper.GetIp(userTokenArray[i].MachineId))
                {
                    continue;
                }

                try
                {
                    lock (userTokenArray[i])
                    {
                        //清除缓存字典
                        Program.Logger.InfoFormat("clear ip is {0}", userTokenArray[i].ConnectSocket.RemoteEndPoint.ToString());
                        SocketDictionary.Remove(userTokenArray[i].MachineId);
                        AsyncSocketSvr.CloseClientSocket(userTokenArray[i]);
                    }
                }
                catch (Exception E)
                {
                    Program.Logger.ErrorFormat("Daemon thread check timeout socket error, message: {0}", E.Message);
                    Program.Logger.Error(E.StackTrace);
                }
            }
        }
示例#3
0
        /// <summary>
        /// 保持连接状态,接收客户端发来的消息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="webSocket"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task Wait(HttpContext context, WebSocket webSocket, int id)
        {
            var buffer = new byte[1024 * 1];
            var result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            // 接收客户端消息,直到拿到关闭消息为止
            while (!result.CloseStatus.HasValue)
            {
                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);

            SocketDictionary.Remove(id);
        }
示例#4
0
        private void sendToTerminal(AsyncSocketServer m_asyncSocketServer, string machineId, string ip, byte[] byteInfo, int sendLength, int count)
        {
            AsyncSocketUserToken dicUserToken = SocketDictionary.Get(machineId);

            if (dicUserToken != null)
            {
                Program.Logger.InfoFormat("machine id was {0}", machineId);
                dicUserToken.SendEventArgs.SetBuffer(byteInfo.Skip(2).ToArray(), 0, sendLength);
                for (int j = 0; j < count; j++)
                {
                    bool willRaiseEvent = dicUserToken.ConnectSocket.SendAsync(dicUserToken.SendEventArgs);
                }
                return;
            }
            else
            {
                AsyncSocketUserToken[] list = null;
                m_asyncSocketServer.AsyncSocketUserTokenList.CopyList(ref list);
                for (int i = 0; i < list.Length; i++)
                {
                    if (list[i].MachineId == machineId)
                    {
                        if (MachineHelper.IsOnline(machineId))
                        {
                            ip = MachineHelper.GetIp(machineId);
                        }
                        // Program.Logger.InfoFormat("loop ip is {0}", ip);
                        if (list[i].ConnectSocket.RemoteEndPoint.ToString() == ip)
                        {
                            list[i].SendEventArgs.SetBuffer(byteInfo.Skip(2).ToArray(), 0, sendLength);

                            for (int j = 0; j < count; j++)
                            {
                                bool willRaiseEvent = list[i].ConnectSocket.SendAsync(list[i].SendEventArgs);
                            }

                            break;
                        }
                    }
                }
            }
        }
示例#5
0
        /// <summary>
        /// 处理websocket请求
        /// </summary>
        /// <param name="context">请求上下文</param>
        /// <param name="next">中间件之后执行</param>
        /// <returns></returns>
        public async Task WebSocktHandlerAsync(HttpContext context, Func <Task> next)
        {
            if (context.Request.Path.Value.Contains("/ws"))
            {
                var id   = int.Parse(context.Request.Query["id"].FirstOrDefault());          // 获取商户id
                var type = context.Request.Query["type"].FirstOrDefault();
                if (context.WebSockets.IsWebSocketRequest)
                {
                    var webSocket = await context.WebSockets.AcceptWebSocketAsync();

                    if (type == "client")
                    {
                        // 客户端连接
                        // 每个商户id只允许一个websocket连接
                        if (ClientSocketDictionary.ContainsKey(id))
                        {
                            var oldSocket = ClientSocketDictionary[id];
                            try
                            {
                                // 未知的原因会导致websocket对象释放掉,已释放的对象不用再次关闭
                                await oldSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "由于一个新的连接进入,您被迫下线了!", CancellationToken.None);
                            }
                            catch (Exception)
                            {
                            }
                            ClientSocketDictionary[id] = webSocket;
                        }
                        else
                        {
                            ClientSocketDictionary.Add(id, webSocket);
                        }
                        await Wait(context, webSocket, id);

                        ClientSocketDictionary.Remove(id);
                    }
                    else
                    {
                        // 每个商户id只允许一个websocket连接
                        if (SocketDictionary.ContainsKey(id))
                        {
                            var oldSocket = SocketDictionary[id];
                            try
                            {
                                // 未知的原因会导致websocket对象释放掉,已释放的对象不用再次关闭
                                await oldSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "由于一个新的连接进入,您被迫下线了!", CancellationToken.None);
                            }
                            catch (Exception)
                            {
                            }
                            SocketDictionary[id] = webSocket;
                        }
                        else
                        {
                            SocketDictionary.Add(id, webSocket);
                        }
                        await Wait(context, webSocket, id);

                        SocketDictionary.Remove(id);
                    }
                }
                else
                {
                    context.Response.StatusCode = 400;
                }
            }
            else
            {
                await next();
            }
        }