Example #1
0
        public void Close()
        {
            if (socket == null)
            {
                return;
            }

            Logger.Info($" [{GetHashCode()}] 连接断开");


            var socket_ = socket;

            socket = null;



            try
            {
                if (socket_.Connected)
                {
                    socket_.Close();
                    socket_.Dispose();
                }
                //socket_.Shutdown(SocketShutdown.Both);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

            try
            {
                connector?.Close();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

            try
            {
                Conn_OnDisconnected?.Invoke(this);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
Example #2
0
        // This method is invoked when an asynchronous receive operation completes.
        // If the remote host closed the connection, then the socket is closed.
        // If data was received then the data is echoed back to the client.
        //
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            try
            {
                //读取数据
                DeliveryConnection conn = (DeliveryConnection)e.UserToken;
                if (conn != null)
                {
                    // check if the remote host closed the connection
                    if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
                    {
                        //读取数据
                        conn.AppendData(new ArraySegment <byte>(e.Buffer, e.Offset, e.BytesTransferred));

                        //byte[] buffData = DataPool.BytesGet(receiveBufferSize);
                        byte[] buffData = new byte[receiveBufferSize];
                        e.SetBuffer(buffData, 0, buffData.Length);

                        // start loop
                        //继续接收. 为什么要这么写,请看Socket.ReceiveAsync方法的说明
                        if (!conn.socket.ReceiveAsync(e))
                        {
                            ProcessReceive(e);
                        }
                    }
                    else
                    {
                        conn.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }