Example #1
0
        /// <summary>
        /// receive/send message complete an asynchronous operation
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="asyncEventArgs"></param>
        void IO_Completed(object sender, SocketAsyncEventArgs asyncEventArgs)
        {
            AsyncSocketUserToken userToken = asyncEventArgs.UserToken as AsyncSocketUserToken;

            try
            {
                lock (userToken)
                {
                    if (asyncEventArgs.LastOperation == SocketAsyncOperation.Receive)
                    {
                        userToken.ActiveDateTime = DateTime.Now;
                        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);
                Console.WriteLine("IO_Completed {0} error, message: {1}", userToken.ConnectSocket, E.Message);
                Console.WriteLine(E.StackTrace);
            }
        }
 public void Remove(AsyncSocketUserToken userToken)
 {
     lock (m_list)
     {
         m_list.Remove(userToken);
     }
 }
Example #3
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);

            Console.WriteLine("Client connection disconnected. {0}", socketInfo);
            try
            {
                userToken.ConnectSocket.Shutdown(SocketShutdown.Both);
            }
            catch (Exception E)
            {
                Program.Logger.ErrorFormat("CloseClientSocket Disconnect client {0} error, message: {1}", socketInfo, E.Message);
                Console.WriteLine("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);
        }
 public void Add(AsyncSocketUserToken userToken)
 {
     lock (m_list)
     {
         m_list.Add(userToken);
     }
 }
 public void CopyList(ref AsyncSocketUserToken[] array)
 {
     lock (m_list)
     {
         array = new AsyncSocketUserToken[m_list.Count];
         m_list.CopyTo(array);
     }
 }
 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);
     }
 }
Example #7
0
        /// <summary>
        /// 根据最大连接数,,初始化SOCKET连接池,并入栈,完成端口绑定RECIVE/SEND
        /// </summary>
        public void Init()
        {
            //预分配一组,可以重复使用的SOCKET连接池
            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);
            }
        }
Example #8
0
        /// <summary>
        /// 协议类绑定
        /// </summary>
        /// <param name="userToken"></param>
        private void BuildingSocketInvokeElement(AsyncSocketUserToken userToken)
        {
            //todo:可以根据端口绑定相应的处理协议,待添加
            //气体传感器协议
            //  userToken.AsyncSocketInvokeElement = new HWSmellSensor(this,userToken);
            //土壤传感器协议
            userToken.AsyncSocketInvokeElement = new LHSoilSensor(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);
            }
        }
Example #9
0
        private void ProcessReceive(SocketAsyncEventArgs receiveEventArgs)
        {
            //       Console.WriteLine("begin ProcessReceive ");

            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对象,并且没有绑定协议对象,则进行协议对象绑定
                {
                    //todo:根据端口绑定协议对像
                    BuildingSocketInvokeElement(userToken);
                }
                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);
            }
            //Console.WriteLine("end ProcessReceive ");
        }
        public AsyncSocketInvokeElement(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken)
        {
            m_asyncSocketServer = asyncSocketServer;
            //   AsyncSocketUserToken.SendAsyncState = false;
            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;
        }
Example #11
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);
            }
        }
Example #12
0
        /// <summary>
        /// 处理接收到的SOCKET,添加至连接表,并投递接收请求。
        /// </summary>
        /// <param name="acceptEventArgs"></param>
        private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs)
        {
            Console.WriteLine(System.DateTime.Now + "  ProcessAccept");

            Program.Logger.InfoFormat("Client connection accepted. Local Address: {0}, Remote Address: {1}",
                                      acceptEventArgs.AcceptSocket.LocalEndPoint, acceptEventArgs.AcceptSocket.RemoteEndPoint);
            Console.WriteLine("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;
            //todo:后期需要根据收到的心跳包特殊定制:
            userToken.StrQueryCommand = "0102030405060708090001020304050607080900";

            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);

                Console.WriteLine("Accept client {0} error, message: {1}", userToken.ConnectSocket, E.Message);
            }

            StartAccept(acceptEventArgs); //把当前异步事件释放,等待下次连接
        }