示例#1
0
 public BaseSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
     : base(asyncSocketServer, asyncSocketUserToken)
 {
     m_userName   = "";
     m_logined    = false;
     m_socketFlag = "";
 }
示例#2
0
        private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs)
        {
            Program.Logger.InfoFormat("Client connection accepted. Local Address: {0}, Remote Address: {1}",
                                      acceptEventArgs.AcceptSocket.LocalEndPoint, acceptEventArgs.AcceptSocket.RemoteEndPoint);

            AsyncSocketUserToken userToken = m_asyncSocketUserTokenPool.Pop();

            m_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)
            {
                Program.Logger.ErrorFormat("Accept client {0} error, message: {1}", userToken.ConnectSocket, E.Message);
                Program.Logger.Error(E.StackTrace);
            }

            StartAccept(acceptEventArgs); //把当前异步事件释放,等待下次连接
        }
示例#3
0
        private void BuildingSocketInvokeElement(AsyncSocketUserToken userToken)
        {
            //byte flag = userToken.ReceiveEventArgs.Buffer[userToken.ReceiveEventArgs.Offset];

            /*
             * if (flag == (byte)SocketFlag.Upload)
             *  userToken.AsyncSocketInvokeElement = new UploadSocketProtocol(this, userToken);
             * else if (flag == (byte)SocketFlag.Download)
             *  userToken.AsyncSocketInvokeElement = new DownloadSocketProtocol(this, userToken);
             * else if (flag == (byte)SocketFlag.RemoteStream)
             *  userToken.AsyncSocketInvokeElement = new RemoteStreamSocketProtocol(this, userToken);
             * else if (flag == (byte)SocketFlag.Throughput)
             *  userToken.AsyncSocketInvokeElement = new ThroughputSocketProtocol(this, userToken);
             * else if (flag == (byte)SocketFlag.Control)
             *  userToken.AsyncSocketInvokeElement = new ControlSocketProtocol(this, userToken);
             * else if (flag == (byte)SocketFlag.LogOutput)
             *  userToken.AsyncSocketInvokeElement = new LogOutputSocketProtocol(this, userToken);
             * if (userToken.AsyncSocketInvokeElement != null)
             * {
             *  Program.Logger.InfoFormat("Building socket invoke element {0}.Local Address: {1}, Remote Address: {2}",
             *      userToken.AsyncSocketInvokeElement, userToken.ConnectSocket.LocalEndPoint, userToken.ConnectSocket.RemoteEndPoint);
             * }
             * */

            userToken.AsyncSocketInvokeElement = new HandelSocketProtocol(this, userToken);
        }
示例#4
0
        void IO_Completed(object sender, SocketAsyncEventArgs asyncEventArgs)
        {
            AsyncSocketUserToken userToken = asyncEventArgs.UserToken as AsyncSocketUserToken;

            userToken.ActiveDateTime = DateTime.Now;
            try
            {
                lock (userToken)
                {
                    if (asyncEventArgs.LastOperation == SocketAsyncOperation.Receive)
                    {
                        ProcessReceive(asyncEventArgs);
                    }
                    else if (asyncEventArgs.LastOperation == SocketAsyncOperation.Send)
                    {
                        ProcessSend(asyncEventArgs);
                    }
                    else
                    {
                        throw new ArgumentException("The last operation completed on the socket was not a receive or send");
                    }
                }
            }
            catch (Exception E)
            {
                Program.Logger.ErrorFormat("IO_Completed {0} error, message: {1}", userToken.ConnectSocket, E.Message);
                Program.Logger.Error(E.StackTrace);
            }
        }
示例#5
0
 public void Remove(AsyncSocketUserToken userToken)
 {
     lock (m_list)
     {
         m_list.Remove(userToken);
     }
 }
示例#6
0
 public void Add(AsyncSocketUserToken userToken)
 {
     lock (m_list)
     {
         m_list.Add(userToken);
     }
 }
示例#7
0
 public void CopyList(ref AsyncSocketUserToken[] array)
 {
     lock (m_list)
     {
         array = new AsyncSocketUserToken[m_list.Count];
         m_list.CopyTo(array);
     }
 }
示例#8
0
        private void ProcessReceive(SocketAsyncEventArgs receiveEventArgs)
        {
            AsyncSocketUserToken userToken = receiveEventArgs.UserToken as AsyncSocketUserToken;

            if (userToken.ConnectSocket == null)
            {
                return;
            }
            userToken.ActiveDateTime = DateTime.Now;
            if (userToken.ReceiveEventArgs.BytesTransferred > 0 && userToken.ReceiveEventArgs.SocketError == SocketError.Success)
            {
                int offset = userToken.ReceiveEventArgs.Offset;
                int count  = userToken.ReceiveEventArgs.BytesTransferred;
                if ((userToken.AsyncSocketInvokeElement == null) & (userToken.ConnectSocket != null)) //存在Socket对象,并且没有绑定协议对象,则进行协议对象绑定
                {
                    BuildingSocketInvokeElement(userToken);
                    //offset = offset + 1;
                    //count = count - 1;
                }

                if (userToken.AsyncSocketInvokeElement == null) //如果没有解析对象,提示非法连接并关闭连接
                {
                    Program.Logger.WarnFormat("Illegal client connection. Local Address: {0}, Remote Address: {1}", userToken.ConnectSocket.LocalEndPoint,
                                              userToken.ConnectSocket.RemoteEndPoint);
                    CloseClientSocket(userToken);
                }
                else
                {
                    if (count > 0) //处理接收数据
                    {
                        if (!userToken.AsyncSocketInvokeElement.ProcessReceive(userToken.ReceiveEventArgs.Buffer, offset, count))
                        { //如果处理数据返回失败,则断开连接
                            CloseClientSocket(userToken);
                        }
                        else //否则投递下次介绍数据请求
                        {
                            bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投递接收请求
                            if (!willRaiseEvent)
                            {
                                ProcessReceive(userToken.ReceiveEventArgs);
                            }
                        }
                    }
                    else
                    {
                        bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投递接收请求
                        if (!willRaiseEvent)
                        {
                            ProcessReceive(userToken.ReceiveEventArgs);
                        }
                    }
                }
            }
            else
            {
                CloseClientSocket(userToken);
            }
        }
示例#9
0
 public UploadSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
     : base(asyncSocketServer, asyncSocketUserToken)
 {
     m_socketFlag = "Upload";
     m_fileName   = "";
     m_fileStream = null;
     lock (m_asyncSocketServer.UploadSocketProtocolMgr)
     {
         m_asyncSocketServer.UploadSocketProtocolMgr.Add(this);
     }
 }
示例#10
0
 public void Push(AsyncSocketUserToken item)
 {
     if (item == null)
     {
         throw new ArgumentException("Items added to a AsyncSocketUserToken cannot be null");
     }
     lock (m_pool)
     {
         m_pool.Push(item);
     }
 }
示例#11
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);
            }
        }
示例#12
0
        public LogOutputSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
            : base(asyncSocketServer, asyncSocketUserToken)
        {
            m_socketFlag     = "LogOutput";
            m_logFixedBuffer = new LogFixedBuffer();
            lock (Program.AsyncSocketSvr.LogOutputSocketProtocolMgr)
            {
                Program.AsyncSocketSvr.LogOutputSocketProtocolMgr.Add(this);
            }

            SendResponse();
        }
示例#13
0
 public DownloadSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
     : base(asyncSocketServer, asyncSocketUserToken)
 {
     m_socketFlag = "Download";
     m_fileName   = "";
     m_fileStream = null;
     m_sendFile   = false;
     m_packetSize = 64 * 1024;
     lock (m_asyncSocketServer.DownloadSocketProtocolMgr)
     {
         m_asyncSocketServer.DownloadSocketProtocolMgr.Add(this);
     }
 }
示例#14
0
        public AsyncSocketInvokeElement(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
        {
            m_asyncSocketServer    = asyncSocketServer;
            m_asyncSocketUserToken = asyncSocketUserToken;

            m_netByteOrder = false;

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

            m_sendAsync = false;

            m_connectDT = DateTime.UtcNow;
            m_activeDT  = DateTime.UtcNow;
        }
示例#15
0
        private bool ProcessSend(SocketAsyncEventArgs sendEventArgs)
        {
            AsyncSocketUserToken userToken = sendEventArgs.UserToken as AsyncSocketUserToken;

            if (userToken.AsyncSocketInvokeElement == null)
            {
                return(false);
            }
            userToken.ActiveDateTime = DateTime.Now;
            if (sendEventArgs.SocketError == SocketError.Success)
            {
                return(userToken.AsyncSocketInvokeElement.SendCompleted()); //调用子类回调函数
            }
            else
            {
                CloseClientSocket(userToken);
                return(false);
            }
        }
示例#16
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;
                        }
                    }
                }
            }
        }
示例#17
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);

            Program.Logger.InfoFormat("Client connection disconnected. {0}", socketInfo);

            try
            {
                //清除redis连接

                /*
                 * if(!string.IsNullOrEmpty(userToken.MachineId))
                 * {
                 *  RedisHelper helper = new RedisHelper(0);
                 *  if (helper.KeyExists(userToken.MachineId))
                 *  {
                 *      helper.KeyDelete(userToken.MachineId);
                 *  }
                 *
                 * }
                 */
                userToken.MachineId = "";
                userToken.ConnectSocket.Shutdown(SocketShutdown.Both);
            }
            catch (Exception E)
            {
                Program.Logger.ErrorFormat("CloseClientSocket Disconnect client {0} error, message: {1}", socketInfo, E.Message);
            }
            m_maxNumberAcceptedClients.Release();
            m_asyncSocketUserTokenPool.Push(userToken);
            m_asyncSocketUserTokenList.Remove(userToken);
            userToken.ConnectSocket.Close();
            userToken.ConnectSocket = null; //释放引用,并清理缓存,包括释放协议对象等资源
        }
示例#18
0
        //处理机器消息
        public byte[] HandleHexByte(byte[] byteInfo, AsyncSocketUserToken m_asyncSocketUserToken, AsyncSocketServer m_asyncSocketServer)
        {
            //Program.Logger.InfoFormat("receive message is {0}, machine id is {1}", ByteHelper.byteToHexStr(byteInfo), m_asyncSocketUserToken.MachineId);
            //包头
            string infoHead = byteInfo[0].ToString();

            //保活
            if (infoHead == "57")
            {
                //Program.Logger.InfoFormat("machine id is {0}", m_asyncSocketUserToken.MachineId);
                if (string.IsNullOrEmpty(m_asyncSocketUserToken.MachineId) || !MachineHelper.IsOnline(m_asyncSocketUserToken.MachineId))
                {
                    return(new byte[0]);
                }
                return(byteInfo);
            }

            if (infoHead == "72")
            {
                //大小
                int infoSize = int.Parse(ByteHelper.GenerateRealityData(byteInfo.Skip(1).Take(2).ToArray(), "intval"));

                byte[] deencryData = byteInfo;//解密算法
                //验证码
                string infoVerify = byteInfo[3].ToString();
                //数据
                byte[] data = ByteHelper.Deencryption(infoSize, byteInfo.Skip(4).Take(infoSize).ToArray());
                //验证是否为有效包

                if (!IsValidPackage(infoVerify, data))
                {
                    return(new byte[0]);
                }

                //不签到不回复
                string commandStr = ByteHelper.Ten2Hex(data[0].ToString()).ToUpper();

                if (commandStr != "41" && commandStr != "30")
                {
                    if (string.IsNullOrEmpty(m_asyncSocketUserToken.MachineId))
                    {
                        return(new byte[0]);
                    }
                }

                try
                {
                    //处理机器上传指令的逻辑
                    return(new MachinePush().PushLogic(commandStr, byteInfo, data, m_asyncSocketUserToken));
                }
                catch (Exception e)
                {
                    //MessageBox.Show(e.Message);
                    return(new byte[0]);
                }
            }
            else if (infoHead == "73")  //推送
            {
                int    sendLength = byteInfo.Length - 2;
                string ip         = string.Empty;

                byte[] sendInfo = new byte[byteInfo.Length];
                byteInfo.CopyTo(sendInfo, 0);
                int size73 = int.Parse(ByteHelper.GenerateRealityData(byteInfo.Skip(3).Take(2).ToArray(), "intval"));
                ByteHelper.Deencryption(size73, byteInfo.Skip(6).Take(size73).ToArray()).CopyTo(byteInfo, 6);
                string machineId10 = ByteHelper.GenerateRealityData(byteInfo.Skip(7).Take(12).ToArray(), "stringval");

                ip = MachineHelper.GetIp(machineId10);

                if (sendLength > 0 && !string.IsNullOrEmpty(ip))
                {
                    sendToTerminal(m_asyncSocketServer, machineId10, ip, sendInfo, sendLength, 3);

                    /*
                     * SetTimeout(5000, delegate {
                     *  Program.Logger.InfoFormat("loop machineId is {0}, loop ip is {1}, message is {2}", machineId10, ip, ByteHelper.byteToHexStr(sendInfo));
                     *  sendToTerminal(m_asyncSocketServer,machineId10,ip, sendInfo, sendLength, 1);
                     * }, machineId10, byteInfo);
                     */
                }

                //x[0].co
                return(new byte[0]);
            }
            else
            {
                try
                {
                    string ipAndMessage         = ByteHelper.GenerateRealityData(byteInfo, "stringval");
                    string ip                   = ipAndMessage.Split("~")[0];
                    byte[] sendByte             = ByteHelper.strToToHexByte(ipAndMessage.Split("~")[1]);
                    AsyncSocketUserToken[] list = null;
                    m_asyncSocketServer.AsyncSocketUserTokenList.CopyList(ref list);
                    for (int i = 0; i < list.Length; i++)
                    {
                        if (list[i].ConnectSocket.RemoteEndPoint.ToString() == ip)
                        {
                            list[i].SendEventArgs.SetBuffer(sendByte, 0, sendByte.Length);
                            bool willRaiseEvent = list[i].ConnectSocket.SendAsync(list[i].SendEventArgs);
                            break;
                        }
                    }
                }
                catch
                {
                    //Program.Logger.InfoFormat("the first by sent was {0}", byteInfo[0]);

                    return(new byte[0]);
                }


                return(new byte[0]);
            }
        }
示例#19
0
 public ThroughputSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
     : base(asyncSocketServer, asyncSocketUserToken)
 {
     m_socketFlag = "Throughput";
 }
 public RemoteStreamSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
     : base(asyncSocketServer, asyncSocketUserToken)
 {
     m_socketFlag = "RemoteStream";
     m_fileStream = null;
 }
示例#21
0
 public ControlSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
     : base(asyncSocketServer, asyncSocketUserToken)
 {
     m_socketFlag = "Control";
 }