Beispiel #1
0
 public void Add(AsyncSocketUserToken userToken)
 {
     lock (m_list)
     {
         m_list.Add(userToken);
     }
 }
 public AsyncProtocolInvokeElement(ServerSocket server, AsyncSocketUserToken userToken)
 {
     this.server    = server;
     this.userToken = userToken;
     isSending      = false;
     sendData       = new SendData();
 }
Beispiel #3
0
        private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs)
        {
            App.Logger.Info("Client connection accepted. Local Address: {0}, Remote Address: {1}",
                            acceptEventArgs.AcceptSocket.LocalEndPoint, acceptEventArgs.AcceptSocket.RemoteEndPoint);

            AsyncSocketUserToken userToken = AsyncSocketUserTokenPool.Pop();

            AsyncSocketUserTokenList.Add(userToken); //添加到正在连接列表
            userToken.ConnectSocket   = acceptEventArgs.AcceptSocket;
            userToken.ConnectDateTime = DateTime.Now;

            try
            {
                bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投递接收请求
                if (!willRaiseEvent)
                {
                    lock (userToken)
                    {
                        ProcessReceive(userToken.ReceiveEventArgs);
                    }
                }
            }
            catch (Exception E)
            {
                App.Logger.Error("Accept client {0} error, message: {1}", userToken.ConnectSocket, E.Message);
                App.Logger.Error(E.StackTrace);
            }

            StartAccept(acceptEventArgs); //把当前异步事件释放,等待下次连接
        }
Beispiel #4
0
 private void button4_Click(object sender, EventArgs e)
 {
     this.label12.Text = "";
     try
     {
         int       count = dtuServer.AsyncSocketUserTokenList.count();
         DataTable dt    = new DataTable();
         dt.Columns.Add("IP");
         dt.Columns.Add("Port");
         dt.Columns.Add("deviceNo");
         for (int i = 0; i < count; i++)
         {
             try
             {
                 AsyncSocketUserToken token = dtuServer.AsyncSocketUserTokenList.UserTokenList[i];
                 DataRow dr = dt.NewRow();
                 dr[0] = ((IPEndPoint)token.ConnectedSocket.RemoteEndPoint).Address.ToString();
                 dr[1] = ((IPEndPoint)token.ConnectedSocket.RemoteEndPoint).Port;
                 dr[2] = token.DeviceInfo != null ? token.DeviceInfo.DeviceNo : "无设备";
                 dt.Rows.Add(dr);
             }
             catch { }
         }
         this.dataGridView1.DataSource = dt;
         this.label11.Text             = dt.Rows.Count.ToString();
         this.label12.ForeColor        = Color.Green;
         this.label12.Text             = "更新成功";
     }
     catch
     {
         this.label12.ForeColor = Color.Red;
         this.label12.Text      = "更新失败";
     }
 }
 public SocketBuffer(bool isReady, List <byte> buffer, AsyncSocketUserToken remoteSock)
 {
     m_ReceivedBuffer.Clear();
     m_IsReady = isReady;
     m_ReceivedBuffer.AddRange(buffer);  //不要引用,而是要复制
     m_RemoteSock = remoteSock;
 }
Beispiel #6
0
        private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs)
        {
            Console.WriteLine("Client connection accepted. Local Address: {0}, Remote Address: {1}",
                              acceptEventArgs.AcceptSocket.LocalEndPoint, acceptEventArgs.AcceptSocket.RemoteEndPoint);

            AsyncSocketUserToken userToken = AsyncSocketUserTokenPool.Pop();

            AsyncSocketUserTokenList.Add(userToken);
            userToken.ConnectSocket   = acceptEventArgs.AcceptSocket;
            userToken.ConnectDateTime = DateTime.Now;

            try
            {
                bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs);
                if (!willRaiseEvent)
                {
                    lock (userToken)
                    {
                        ProcessReceive(userToken.ReceiveEventArgs);
                    }
                }
            }
            catch (Exception E)
            {
                Console.WriteLine("Accept client {0} error, message: {1}", userToken.ConnectSocket, E.Message);
                Console.WriteLine(E.StackTrace);
            }

            StartAccept(acceptEventArgs);
        }
        /// <summary>
        /// 通过SOCKET也可以查找一个控制器
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public Controller Get(AsyncSocketUserToken usertoken)
        {
            Controller controller = null;

            try
            {
                if (usertoken == null)
                {
                    return(null);
                }
                Socket socket = usertoken.ConnectSocket;
                if (socket.RemoteEndPoint == null)
                {
                    return(null);
                }
                IPEndPoint point  = socket.RemoteEndPoint as IPEndPoint;
                byte[]     ipByte = point.Address.GetAddressBytes();
                long       ip     = Bytes2Long(ipByte);
                controller = Get(ip);
            }
            catch (Exception e)
            {
                Logger.Instance().ErrorFormat("ControllerManager::Get() Error Message={0}", e.Message);
            }
            return(controller);
        }
 /// <summary>
 /// 将一个SOCKET的IP地址转换成long
 /// </summary>
 /// <param name="sock"></param>
 /// <returns></returns>
 public static long GetLongIPFromSocket(AsyncSocketUserToken sockToken)
 {
     if (sockToken != null)
     {
         Socket sock = sockToken.ConnectSocket;
         if (sock != null && sock.RemoteEndPoint != null)
         {
             IPEndPoint endpoint  = sock.RemoteEndPoint as IPEndPoint;
             byte[]     addrBytes = endpoint.Address.GetAddressBytes();
             if (addrBytes.Length != 4)
             {
                 Logger.Instance().Debug("GetLongIPFromSocket()->endpoint.GetAddressBytes() Error");
                 return(0);
             }
             long ip = addrBytes[0] & 0xFF;
             ip += addrBytes[1] << 8 & 0x00FF00;
             ip += addrBytes[2] << 16 & 0x00FF0000;
             ip += addrBytes[3] << 24 & 0x00FF000000;
             return(ip);
         }
         else
         {
             return(0);
         }
     }
     return(0);
 }
Beispiel #9
0
        // 创建角色
        private static void CreateRole(AsyncSocketUserToken client, JSONObject data)
        {
            int    userId   = (int)data["userId"].i;
            string roleName = data["roleName"].str;

            DataPacket dp    = NetWorkManager.Instance.dataPacketPool.Pop();
            int        error = 0;
            Role       role  = null;

            if (string.IsNullOrEmpty(roleName))
            {
                error = 1004;
            }

            if (error == 0 && DataManager.Instance.RoleIsExisting(roleName))
            {
                error = 1003;
            }

            if (error == 0)
            {
                role          = ConfigManager.Instance.GetRole(1000);
                role.roleName = roleName;
                error         = DataManager.Instance.AddNewRole(userId, role);
            }
            if (role != null)
            {
                dp.Data.AddField("roleInfo", role.ToJson());
            }
            dp.Add(data["cmd"].i, error);
            Send(client, dp);
        }
        /// <summary>
        /// 响应串口层上传的数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void ReceiveData(object sender, DataTransmissionEventArgs args)
        {
            AsyncSocketUserToken socket = args.Token;

            if (socket == null)
            {
                return;
            }
            long         ip     = ControllerManager.GetLongIPFromSocket(socket);
            SocketBuffer buffer = null;

            lock (m_HashReceivedBuffer)
            {
                if (m_HashReceivedBuffer.ContainsKey(ip))
                {
                    buffer = (SocketBuffer)m_HashReceivedBuffer[ip];
                }
                else
                {
                    buffer = new SocketBuffer();
                    m_HashReceivedBuffer.Add(ip, buffer);
                }
                buffer.RemoteSock = socket;
                //lxm 20161013修改,传入的字节流要进行一次转换,将字符字节两两合成一个16进制数据,比如:'F'和'5' 合成0xF5
                buffer.ReceivedCharBuffer.AddRange(args.EventData);
                args.EventData.Clear();
                buffer.IsReady = Char2Hex(buffer);
                if (buffer.IsReady)
                {
                    m_SemReceiveCommand.Release(1);
                }
            }
        }
Beispiel #11
0
        private static void Send(AsyncSocketUserToken client, DataPacket dp)
        {
            MyLog.Log("--->{0}", dp.Tojson());

            client.SendMessage(dp.Tojson());
            NetWorkManager.Instance.dataPacketPool.Push(dp);
        }
Beispiel #12
0
        // 心跳
        private static void Heartbeat(AsyncSocketUserToken client, JSONObject data)
        {
            DataPacket dp = NetWorkManager.Instance.dataPacketPool.Pop();

            dp.Add(data["cmd"].i, 0);
            Send(client, dp);
        }
Beispiel #13
0
        public static void Parse(AsyncSocketUserToken client, string args)
        {
            MyLog.Log("<---{0}", args);

            JSONObject data = new JSONObject(args);
            CMD        cmd  = (CMD)data["cmd"].i;

            switch (cmd)
            {
            case CMD.Heartbeat: Heartbeat(client, data); break;

            case CMD.Login: Login(client, data); break;

            case CMD.Register: Register(client, data); break;

            //case CMD.GetRole: GetRole(client, data); break;
            case CMD.CreateRole: CreateRole(client, data); break;

            case CMD.EnterGame: EnterGame(client, data); break;

            //case CMD.SelectRole: SelectRole(client, data); break;
            case CMD.EnterBattleScene: EnterBattleScene(client, data); break;
            //case CMD.Attack: Attack(client, data); break;

            default: MyLog.Error("未知 CMD " + cmd); break;
            }
        }
Beispiel #14
0
        private void IO_Completed(object sender, SocketAsyncEventArgs oEventArgs)
        {
            AsyncSocketUserToken userToken = oEventArgs.UserToken as AsyncSocketUserToken;

            userToken.ActiveDateTime = DateTime.Now;
            try
            {
                lock (userToken)
                {
                    if (oEventArgs.LastOperation == SocketAsyncOperation.Receive)
                    {
                        ProcessReceive(oEventArgs);
                    }
                    else if (oEventArgs.LastOperation == SocketAsyncOperation.Send)
                    {
                        ProcessSend(oEventArgs);
                    }
                    else
                    {
                        throw new ArgumentException("The last operation completed on the socket was not a receive or send");
                    }
                }
            }
            catch (Exception e)
            {
                App.Logger.Error("IO_Completed {0} error, message: {1}", userToken.ConnectSocket, e.Message);
                App.Logger.Error(e.StackTrace);
            }
        }
Beispiel #15
0
        public void CloseSocket(AsyncSocketUserToken userToken)
        {
            if (userToken.ConnectSocket == null)
            {
                return;
            }
            string socketInfo = string.Format("Local Address: {0} Remote Address: {1}", userToken.ConnectSocket.LocalEndPoint,
                                              userToken.SendEventArgs.RemoteEndPoint);

            App.Logger.Info("Connection disconnected. {0}", socketInfo);
            try
            {
                userToken.ConnectSocket.Shutdown(SocketShutdown.Both);
            }
            catch (Exception E)
            {
                App.Logger.Info("CloseSocket Disconnect {0} error, message: {1}", socketInfo, E.Message);
            }
            userToken.ConnectSocket.Close();
            userToken.ConnectSocket = null; //释放引用,并清理缓存,包括释放协议对象等资源
            userToken.TokenClose();

            MaxNumberAccepted.Release();
            AsyncSocketUserTokenPool.Push(userToken);
            AsyncSocketUserTokenList.Remove(userToken);
        }
 /// <summary>
 /// 发送给WIFI
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 private void MapIPFromWifi(object sender, DataTransmissionEventArgs args)
 {
     if (args.Token.ConnectSocket != null)
     {
         AsyncSocketUserToken socket = args.Token;
         long       ip         = ControllerManager.GetLongIPFromSocket(socket);
         Controller controller = ControllerManager.Instance().Get(ip);
         if (controller != null)
         {
             if (controller.SocketToken != null)
             {
                 AsyncServer.Instance().CloseClientSocketEx(controller.SocketToken);
             }
             controller.SocketToken = socket;
             if (SocketConnectOrCloseResponse != null)
             {
                 SocketConnectOrCloseResponse(this, new SocketConnectArgs(true, socket));
             }
             //新连接的客户端要对它发送泵类型指令
             if (SendPumpType2Wifi != null)
             {
                 SendPumpType2Wifi(this, new SocketConnectArgs(true, socket));
             }
         }
         else
         {
             if (m_Device != null)
             {
                 m_Device.CloseClientSocket(args.Token);
             }
             Logger.Instance().ErrorFormat("MapIPFromWifi()->ControllerManager.Instance().Get 错误,IP={0}", ip);
             return;
         }
     }
 }
Beispiel #17
0
 public BaseSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
     : base(asyncSocketServer, asyncSocketUserToken)
 {
     m_userName   = "";
     m_logined    = false;
     m_socketFlag = "";
 }
 /// <summary>
 /// 删除序列号
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 private void AntiMapIPFromWifi(object sender, DataTransmissionEventArgs args)
 {
     if (args.Token != null)
     {
         AsyncSocketUserToken socket = args.Token;
         if (socket.ConnectSocket == null || socket.ConnectSocket.RemoteEndPoint == null)
         {
             return;
         }
         if (SocketConnectOrCloseResponse != null)
         {
             SocketConnectOrCloseResponse(this, new SocketConnectArgs(false, socket));
         }
         long       ip         = ControllerManager.GetLongIPFromSocket(socket);
         Controller controller = ControllerManager.Instance().Get(ip);
         if (controller != null)
         {
             controller.SocketToken = null;
         }
         lock (m_HashReceivedBuffer)
         {
             if (m_HashReceivedBuffer.ContainsKey(ip))
             {
                 m_HashReceivedBuffer.Remove(ip);
             }
         }
     }
 }
Beispiel #19
0
        private void ProcessAccept(SocketAsyncEventArgs e)
        {
            try
            {
                SocketAsyncEventArgs readEventArgs = _poolOfRecSendEventArgs.Pop();
                if (readEventArgs != null)
                {
                    readEventArgs.UserToken = new AsyncSocketUserToken(e.AcceptSocket);
                    Interlocked.Increment(ref _connectedSocketCount);
                    _log.WriteLine("Client connection accepted. There are " + _connectedSocketCount + " clients connected to the server");
                    if (!e.AcceptSocket.ReceiveAsync(readEventArgs))
                    {
                        ProcessReceive(readEventArgs);
                    }
                }
                else
                {
                    _log.WriteLine("There are no more available sockets to allocate.");
                }
            }
            catch (SocketException ex)
            {
                AsyncSocketUserToken token = e.UserToken as AsyncSocketUserToken;
                _log.WriteLine("Error when processing data received from" + token.Socket.RemoteEndPoint + ":\r\n" + ex.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            // Accept the next connection request.
            StartAccept(e);
        }
Beispiel #20
0
        private void IO_Completed(object sender, SocketAsyncEventArgs e)
        {
            AsyncSocketUserToken userToken = e.UserToken as AsyncSocketUserToken;

            userToken.ActiveDateTime = DateTime.Now;
            try
            {
                lock (userToken)
                {
                    if (e.LastOperation == SocketAsyncOperation.ReceiveFrom)
                    {
                        ProcessReceive(e);
                    }
                    else if (e.LastOperation == SocketAsyncOperation.SendTo)
                    {
                        ProcessSend(e);
                    }
                    else
                    {
                        throw new ArgumentException("The last operation completed on the socket was not a receive or send");
                    }
                }
            }
            catch (Exception E)
            {
                Console.WriteLine("IO_Completed {0} error, message: {1}", userToken.ConnectSocket, E.Message);
                Console.WriteLine(E.StackTrace);
            }
        }
Beispiel #21
0
 public void Remove(AsyncSocketUserToken userToken)
 {
     lock (m_list)
     {
         m_list.Remove(userToken);
     }
 }
Beispiel #22
0
        public void CloseClientSocket(AsyncSocketUserToken userToken)
        {
            if (userToken.ConnectSocket == null)
            {
                return;
            }
            string socketInfo = string.Format("Local Address: {0} Remote Address: {1}", userToken.ConnectSocket.LocalEndPoint,
                                              userToken.ConnectSocket.RemoteEndPoint);

            Debug.WriteLog.Log(eLogLevel.ell_Debug, "Client connection disconnected. " + socketInfo);
            if (Monitor.TryEnter(lock_obj, 100))
            {
                try
                {
                    TCPProtocol tcp = (TCPProtocol)userToken.AsyncSocketInvokeElement;
                    if (tcp != null && tcp.MessageHandle != null)
                    {
                        userToken.ConnectSocket.Shutdown(SocketShutdown.Both);
                        userToken.ConnectSocket.Close();
                        userToken.ConnectSocket.Dispose();
                        userToken.ConnectSocket = null; //释放引用,并清理缓存,包括释放协议对象等资源
                    }
                }
                catch (Exception E)
                {
                    Debug.WriteLog.Log(eLogLevel.ell_Error, String.Format("CloseClientSocket Disconnect client {0} error, message: {1}", socketInfo, E.ToString()));
                }
                Monitor.Exit(lock_obj);
            }
        }
Beispiel #23
0
 /// <summary>
 /// 控制器的IP,所在货架编号,所在货架行号,以及它的连接SOCKET
 /// </summary>
 /// <param name="ip">控制器的IP</param>
 /// <param name="dockNo">所在货架编号</param>
 /// <param name="rowNo">所在货架行号</param>
 /// <param name="token">连接SOCKET</param>
 public Controller(long ip, int dockNo, int rowNo, AsyncSocketUserToken token = null)
 {
     m_IP          = ip;
     m_DockNo      = dockNo;
     m_RowNo       = rowNo;
     m_SocketToken = token;
 }
Beispiel #24
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="ip">控制器的I</param>
 /// <param name="dockNo">所在货架编号</param>
 /// <param name="rowNo">所在货架行号</param>
 /// <param name="pumpList">正在老化的信息列表</param>
 /// <param name="token">连接SOCKET</param>
 public Controller(long ip, int dockNo, int rowNo, List <AgingPump> pumpList, AsyncSocketUserToken token = null)
 {
     m_IP            = ip;
     m_DockNo        = dockNo;
     m_RowNo         = rowNo;
     m_SocketToken   = token;
     m_AgingPumpList = pumpList;
 }
Beispiel #25
0
 public void CopyList(ref AsyncSocketUserToken[] array)
 {
     lock (m_list)
     {
         array = new AsyncSocketUserToken[m_list.Count];
         m_list.CopyTo(array);
     }
 }
Beispiel #26
0
        private void ProcessMessage(byte[] messageData, AsyncSocketUserToken token, SocketAsyncEventArgs e)
        {
            var value = Encoding.ASCII.GetString(messageData).ToUpper();

            _log.WriteLine("received command: " + Encoding.ASCII.GetString(messageData) + " length:" + messageData.Length);

            switch (value)
            {
            case "HELO":
                Interlocked.Increment(ref _receivedHandShakeCount);
                _sendingQueue.Add(new MessageData {
                    Message = Encoding.ASCII.GetBytes("HI"), Token = token
                });
                break;

            case "CONNECTIONS":

                if (_receivedHandShakeCount > 0)
                {
                    _sendingQueue.Add(new MessageData
                    {
                        Message = Encoding.ASCII.GetBytes(_receivedHandShakeCount.ToString()),
                        Token   = token
                    });
                }
                break;

            case "PRIME":
                if (_receivedHandShakeCount > 0)
                {
                    _sendingQueue.Add(new MessageData {
                        Message = Encoding.ASCII.GetBytes("142339"), Token = token
                    });
                }
                break;

            case "TERMINATE":
                if (_receivedHandShakeCount > 0)
                {
                    int i;
                    _sendingQueue.Add(new MessageData {
                        Message = Encoding.ASCII.GetBytes("BYE"), Token = token
                    });

                    CloseClientSocket(e);
                }
                break;

            default:
            {
                //Ignore all other message.
                //sendingQueue.Add(new MessageData { Message = messageData, Token = token });
                break;
            }
            }
        }
        /// <summary>
        /// 发送读泵状态命令
        /// </summary>
        /// <param name="handle">回调函数对象</param>
        public void SendCmdGetPumpStatus(AsyncSocketUserToken remoteSocket, EventHandler <EventArgs> func, EventHandler <EventArgs> timeoutFunc, byte channel = 0xFF)
        {
            CmdGetPumpStatus cmd = new CmdGetPumpStatus();

            cmd.Channel      = channel;
            cmd.RemoteSocket = remoteSocket;
            long ip = ControllerManager.GetLongIPFromSocket(remoteSocket);

            AddCommand(ip, cmd, func, timeoutFunc);
        }
        /// <summary>
        /// 添加通道号的原因是由于控制器轮询一次6个串口很费时间,不如指定具体的串口
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="queryInterval"></param>
        /// <param name="remoteSocket"></param>
        /// <param name="func"></param>
        /// <param name="timeoutFunc"></param>
        public void SendPumpType(ProductID pid, ushort queryInterval, AsyncSocketUserToken remoteSocket, EventHandler <EventArgs> func, EventHandler <EventArgs> timeoutFunc, byte channel = 0xFF)
        {
            CmdSendPumpType cmd = new CmdSendPumpType(pid, queryInterval);

            cmd.Channel      = channel;
            cmd.RemoteSocket = remoteSocket;
            long ip = ControllerManager.GetLongIPFromSocket(remoteSocket);

            AddCommand(ip, cmd, func, timeoutFunc);
        }
        /// <summary>
        /// 发送老化结束命令
        /// </summary>
        /// <param name="handle">回调函数对象</param>
        public void SendCmdFinishAging(AsyncSocketUserToken remoteSocket, EventHandler <EventArgs> func, byte channel = 0xFF)
        {
            CmdFinishAging cmd = new CmdFinishAging();

            cmd.Channel      = channel;
            cmd.RemoteSocket = remoteSocket;
            long ip = ControllerManager.GetLongIPFromSocket(remoteSocket);

            AddCommand(ip, cmd, func);
        }
        /// <summary>
        /// 发送补电命令
        /// </summary>
        /// <param name="channel">通道号,按位表示例如:2号通道=0x02,3号通道=0x04,4号=0x08</param>
        /// <param name="remoteSocket"></param>
        /// <param name="func"></param>
        public void SendCmdRecharge(byte channel, AsyncSocketUserToken remoteSocket, EventHandler <EventArgs> func)
        {
            CmdRecharge cmd = new CmdRecharge();

            cmd.Channel      = channel;
            cmd.RemoteSocket = remoteSocket;
            long ip = ControllerManager.GetLongIPFromSocket(remoteSocket);

            AddCommand(ip, cmd, func);
        }
Beispiel #31
0
        public AsyncSocketInvokeElement(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
        {
            m_asyncSocketServer = asyncSocketServer;
            m_asyncSocketUserToken = asyncSocketUserToken;

            m_netByteOrder = true;

            m_incomingDataParser = new IncomingDataParser();
            m_outgoingDataAssembler = new OutgoingDataAssembler();

            m_sendAsync = false;

            m_connectDT = DateTime.UtcNow;
            m_activeDT = DateTime.UtcNow;
        }
Beispiel #32
0
        public void CloseClientSocket(AsyncSocketUserToken userToken)
        {
            if (userToken.ConnectSocket == null)
                return;
            string socketInfo = string.Format("Local Address: {0} Remote Address: {1}", userToken.ConnectSocket.LocalEndPoint,
                userToken.ConnectSocket.RemoteEndPoint);
            LogService.LogControl.WriteError(string.Format("Client connection disconnected. {0}", socketInfo));
            try
            {
                userToken.ConnectSocket.Shutdown(SocketShutdown.Both);
            }
            catch (Exception E)
            {
                LogService.LogControl.WriteError(string.Format("CloseClientSocket Disconnect client {0} error, message: {1}", socketInfo, E.Message));
            }
            userToken.ConnectSocket.Close();
            userToken.ConnectSocket = null; //释放引用,并清理缓存,包括释放协议对象等资源

            m_maxNumberAcceptedClients.Release();
            m_asyncSocketUserTokenPool.Push(userToken);
            m_asyncSocketUserTokenList.Remove(userToken);
        }
Beispiel #33
0
        public bool DoSendResult(AsyncSocketUserToken token)
        {
            string commandText = m_outgoingDataAssembler.GetProtocolText();
            byte[] bufferUTF8 = Encoding.UTF8.GetBytes(commandText);
            int totalLength = sizeof(int) + bufferUTF8.Length; //获取总大小
            AsyncSendBufferManager asyncSendBufferManager = token.SendBuffer;
            asyncSendBufferManager.StartPacket();
            asyncSendBufferManager.DynamicBufferManager.WriteInt(totalLength, false); //写入总大小
            asyncSendBufferManager.DynamicBufferManager.WriteInt(bufferUTF8.Length, false); //写入命令大小
            asyncSendBufferManager.DynamicBufferManager.WriteBuffer(bufferUTF8); //写入命令内容
            asyncSendBufferManager.EndPacket();

            bool result = true;
            if (!m_sendAsync)
            {
                int packetOffset = 0;
                int packetCount = 0;
                if (asyncSendBufferManager.GetFirstPacket(ref packetOffset, ref packetCount))
                {
                    m_sendAsync = true;
                    result = m_asyncSocketServer.SendAsyncEvent(token.ConnectSocket, token.SendEventArgs,
                        asyncSendBufferManager.DynamicBufferManager.Buffer, packetOffset, packetCount);
                }
            }
            return result;
        }
Beispiel #34
0
        /// <summary>
        /// 处理分完包后的数据
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public virtual bool ProcessPacket(AsyncSocketUserToken userToken, byte[] buffer, int offset, int count)
        {
            //zhangyang  解析包 生成实体
            byte[] tmpbuffer = new byte[count + 6 + 2];
            try
            {

                Array.Copy(buffer, offset, tmpbuffer, 0, count + 8);
                if (tmpbuffer[0] != ProtocolConst.StartCharacter)
                {
                    //标识该包错误 丢弃并关闭连接
                    return false; //
                }
                Byte iFlag = tmpbuffer[1];//功能包
                switch (iFlag)
                {
                    case (byte)ProtocolFlag.Customer:
                        {
                            break;
                        };
                    case (byte)ProtocolFlag.Driver:
                        {
                            break;
                        }

                }
                // 校验数据的准确性
            #if DEBUG
                LogService.LogControl.WriteError(string.Format(" ReceiveData : %s ", BitConverter.ToString(tmpbuffer)));
            #endif
                SendData(userToken.ConnectSocket, tmpbuffer);

                return true;
            }
            catch (Exception ex)
            {
                // 报错记录日志并关闭连接
                LogService.LogControl.WriteError(string.Format("Error Occured in package[ %s  ] because of  : % s ", BitConverter.ToString(tmpbuffer), ex.Message));
                return false;

            }
        }
Beispiel #35
0
        // public virtual bool ProcessReceive(byte[] buffer, int offset, int count)
        /// <summary>
        /// 接收异步事件返回的数据,用于对数据进行缓存和分包  modified by zhangyang  20140724
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public virtual bool ProcessReceive(AsyncSocketUserToken userToken, int offset, int count)
        {
            m_activeDT = DateTime.UtcNow;

            //拼接数据
            DynamicBufferManager receiveBuffer = m_asyncSocketUserToken.ReceiveBuffer;

            // 写入缓存
            receiveBuffer.WriteBuffer(userToken.ReceiveEventArgs.Buffer, 0, count);
            userToken.DataReceived += count; //增加已读
            bool result = true;

            // 解析包数据 开始符 功能码 包体长度 包体(JSON) 校验码

            //处理数据  // 丢掉脏数据
            userToken.DataReceived = receiveBuffer.DataCount;

            while (receiveBuffer.DataCount > 6) // 长于包头 FF 0a
            {
                while ((receiveBuffer.DataCount > 0) && (receiveBuffer.Buffer[0] != ProtocolConst.StartCharacter))
                {
                    receiveBuffer.Clear(1);
                }
                //按照长度分包
                int packetLength = BitConverter.ToInt32(receiveBuffer.Buffer, 2); //获取包长度
                if (NetByteOrder)
                    packetLength = System.Net.IPAddress.NetworkToHostOrder(packetLength); //把网络字节顺序转为本地字节顺序

                if ((packetLength > 10 * 1024 * 1024) | (receiveBuffer.DataCount > 10 * 1024 * 1024)) //最大Buffer异常保护
                {
                    userToken.DataReceived = 0;
                    return false;
                }
                if ((receiveBuffer.DataCount - 6 - 2) >= packetLength) //收到的数据达到包长度
                {

                    result = ProcessPacket(userToken, receiveBuffer.Buffer, 0, packetLength); //处理分出来的包
                    if (result)
                    {
                        receiveBuffer.Clear(packetLength + 6 + 2); //从缓存中清理
                        userToken.DataReceived -= packetLength + 6 + 2;
                    }
                    else
                        return result;
                }
                else
                {
                    return true;
                }
            }
            return true;
        }
Beispiel #36
0
 private void BuildingSocketInvokeElement(AsyncSocketUserToken userToken)
 {
     /*
      *  modified by zhangyang  20140724
      byte caStart = userToken.ReceiveEventArgs.Buffer[0];
      byte flag = userToken.ReceiveEventArgs.Buffer[userToken.ReceiveEventArgs.Offset];
      if (flag == (byte)ProtocolFlag.Driver)
          userToken.AsyncSocketInvokeElement = new DriverSocketProtocol (this, userToken);
      if (flag == (byte)ProtocolFlag.Customer)
          userToken.AsyncSocketInvokeElement = new ClientSocketProtocol(this, userToken);
      if (userToken.AsyncSocketInvokeElement != null)
      {
          LogService.LogControl.WriteError(string.Format("Building socket invoke element {0}.Local Address: {1}, Remote Address: {2}",
              userToken.AsyncSocketInvokeElement, userToken.ConnectSocket.LocalEndPoint, userToken.ConnectSocket.RemoteEndPoint));
      }
      * */
 }
Beispiel #37
0
 public void Init()
 {
     AsyncSocketUserToken userToken;
     //按照连接数建立读写对象
     for (int i = 0; i < m_numConnections; i++)
     {
         userToken = new AsyncSocketUserToken(m_receiveBufferSize);
         userToken.ReceiveEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
         userToken.SendEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
         m_asyncSocketUserTokenPool.Push(userToken);
     }
 }