Example #1
0
        void Completed(object sender, SocketAsyncEventArgs e)
        {
            IFixedCacheStub <NoBuffSocketStub> stub;

            switch (e.LastOperation)
            {
            //send complated event.
            case SocketAsyncOperation.Send:
                #region Send Completed.

                stub = (IFixedCacheStub <NoBuffSocketStub>)e.UserToken;
                TcpTransportChannel channel = (TcpTransportChannel)stub.Tag;
                //giveback it at first.
                ChannelConst.NoBuffAsyncStubPool.Giveback(stub);
                if (e.SocketError != SocketError.Success && channel.IsConnected)
                {
                    _tracing.Warn(
                        string.Format(
                            "The target channel SendAsync status has incorrectly, so the framework decided to disconnect it.\r\nL: {0}\r\nR: {1}\r\nSocket-Error: {2}\r\nBytesTransferred: {3}\r\n",
                            channel.LocalEndPoint,
                            channel.RemoteEndPoint,
                            e.SocketError,
                            e.BytesTransferred));
                    channel.Disconnect();
                }

                #endregion
                break;

            //send complated event.
            case SocketAsyncOperation.Receive:
                throw new System.Exception("#We can't support NoBuffSocketStub to subscribe the event of Complete for Socket.ReadAsync.");
            }
        }
        /// <summary>
        ///     创建一个新的连接代理器
        /// </summary>
        /// <param name="iep">远程终结点地址</param>
        /// <param name="protocolStack">协议栈</param>
        /// <param name="transactionManager">事务管理器</param>
        /// <returns>如果无法连接到远程地址,则返回null.</returns>
        public static IThriftConnectionAgent Create(IPEndPoint iep, IProtocolStack <ThriftMessage> protocolStack, ThriftMessageTransactionManager transactionManager)
        {
            if (iep == null)
            {
                throw new ArgumentNullException("iep");
            }
            if (protocolStack == null)
            {
                throw new ArgumentNullException("protocolStack");
            }
            if (transactionManager == null)
            {
                throw new ArgumentNullException("transactionManager");
            }
            ITransportChannel transportChannel = new TcpTransportChannel(iep);

            transportChannel.Connect();
            if (!transportChannel.IsConnected)
            {
                return(null);
            }
            IMessageTransportChannel <ThriftMessage> msgChannel = new MessageTransportChannel <ThriftMessage>((IRawTransportChannel)transportChannel, protocolStack, new ThriftProtocolSegmentDataParser((ThriftProtocolStack)protocolStack));

            return(new ThriftConnectionAgent(msgChannel, transactionManager));
        }
        /// <summary>
        ///     创建一个新的连接代理器
        /// </summary>
        /// <param name="iep">远程终结点地址</param>
        /// <param name="protocolStack">协议栈</param>
        /// <param name="transactionManager">事务管理器</param>
        /// <returns>如果无法连接到远程地址,则返回null.</returns>
        /// <exception cref="System.ArgumentNullException">非法参数</exception>
        public static IServerConnectionAgent <BaseMessage> Create(IPEndPoint iep, IProtocolStack protocolStack, MessageTransactionManager transactionManager)
        {
            if (iep == null)
            {
                throw new ArgumentNullException(nameof(iep));
            }
            if (protocolStack == null)
            {
                throw new ArgumentNullException(nameof(protocolStack));
            }
            if (transactionManager == null)
            {
                throw new ArgumentNullException(nameof(transactionManager));
            }
            ITransportChannel transportChannel = new TcpTransportChannel(iep);

            transportChannel.Connect();
            if (!transportChannel.IsConnected)
            {
                return(null);
            }
            IMessageTransportChannel <BaseMessage> msgChannel = new MessageTransportChannel <BaseMessage>((IRawTransportChannel)transportChannel, protocolStack);

            return(new IntellectObjectConnectionAgent(msgChannel, transactionManager));
        }
Example #4
0
        /// <summary>
        /// Creates a new UA-binary transport channel if requested. Null otherwise.
        /// </summary>
        public static ITransportChannel CreateUaBinaryChannel(
            ApplicationConfiguration configuration,
            ITransportWaitingConnection connection,
            EndpointDescription description,
            EndpointConfiguration endpointConfiguration,
            X509Certificate2 clientCertificate,
            X509Certificate2Collection clientCertificateChain,
            ServiceMessageContext messageContext)
        {
            bool useUaTcp = description.EndpointUrl.StartsWith(Utils.UriSchemeOpcTcp);
            bool useHttps = description.EndpointUrl.StartsWith(Utils.UriSchemeHttps);

            // initialize the channel which will be created with the server.
            ITransportChannel channel = null;

            if (useUaTcp)
            {
                channel = new TcpTransportChannel();
            }
#if !NO_HTTPS
            else if (useHttps)
            {
                channel = new HttpsTransportChannel();
            }
#endif

            if (channel == null)
            {
                throw ServiceResultException.Create(
                          StatusCodes.BadProtocolVersionUnsupported,
                          "Unsupported transport profile\r\n");
            }

            // create a UA channel.
            var settings = new TransportChannelSettings {
                Description            = description,
                Configuration          = endpointConfiguration,
                ClientCertificate      = clientCertificate,
                ClientCertificateChain = clientCertificateChain
            };

            if (description.ServerCertificate != null && description.ServerCertificate.Length > 0)
            {
                settings.ServerCertificate = Utils.ParseCertificateBlob(description.ServerCertificate);
            }

            if (configuration != null)
            {
                settings.CertificateValidator = configuration.CertificateValidator.GetChannelValidator();
            }

            settings.NamespaceUris = messageContext.NamespaceUris;
            settings.Factory       = messageContext.Factory;

            channel.Initialize(connection, settings);
            channel.Open();

            return(channel);
        }
Example #5
0
        public void ConnectFailTest()
        {
            TcpTransportChannel transportChannel = new TcpTransportChannel("127.0.0.1", 55555);

            transportChannel.Connect();
            Assert.IsFalse(transportChannel.IsConnected);
            Assert.IsTrue(transportChannel.CommunicationState == CommunicationStates.Closed);
        }
        void ListenerConnected(object sender, IocpPortListenerConnectedEventArgs <BasicPortListenerInfomation> e)
        {
            TcpTransportChannel tcpTransportChannel = new TcpTransportChannel(e.ConnectStream);

            //care disconnect event.
            tcpTransportChannel.Disconnected += TransportChannelDisconnected;
            ChannelCreatedHandler(new LightSingleArgEventArgs <ITransportChannel>(tcpTransportChannel));
        }
Example #7
0
 /// <summary>
 ///     初始化
 /// </summary>
 /// <param name="element">统计类型</param><typeparam name="T">统计类型</typeparam>
 public override void Initialize <T>(T element)
 {
     _channel          = (TcpTransportChannel)((object)element);
     _channel.Opened  += Opened;
     _channel.Opening += Opening;
     _channel.Closing += Closing;
     _channel.Closed  += Closed;
     _channel.Faulted += Faulted;
 }
Example #8
0
 /// <summary>
 ///     关闭统计
 /// </summary>
 public override void Close()
 {
     if (_channel != null)
     {
         _channel.Opened  -= Opened;
         _channel.Opening -= Opening;
         _channel.Closing -= Closing;
         _channel.Closed  -= Closed;
         _channel.Faulted -= Faulted;
         _channel          = null;
     }
 }
Example #9
0
 public static ConnectionAgent GetAgent()
 {
     lock (typeof(ChannelPool))
     {
         if (_agent != null && _agent.GetChannel().IsConnected)
         {
             return(_agent);
         }
         TcpTransportChannel channel = new TcpTransportChannel("172.16.20.18", 20200);
         channel.Connect();
         if (!channel.IsConnected)
         {
             return(null);
         }
         _agent = new ConnectionAgent(new MessageTransportChannel <BaseMessage>(channel, new BASProtocolStack()), Common.TransactionManager);
         return(_agent);
     }
 }
Example #10
0
        void Completed(object sender, SocketAsyncEventArgs e)
        {
            IFixedCacheStub <SocketBuffStub> stub;

            switch (e.LastOperation)
            {
            //send complated event.
            case SocketAsyncOperation.Send:
                #region Send Completed.

                stub = (IFixedCacheStub <SocketBuffStub>)e.UserToken;
                TcpTransportChannel channel = (TcpTransportChannel)stub.Tag;
                if (e.SocketError != SocketError.Success && channel.IsConnected)
                {
                    _tracing.Warn(
                        string.Format(
                            "The target channel SendAsync status has incorrectly, so the framework decided to disconnect it.\r\nL: {0}\r\nR: {1}\r\nSocket-Error: {2}\r\nBytesTransferred: {3}\r\n",
                            channel.LocalEndPoint,
                            channel.RemoteEndPoint,
                            e.SocketError,
                            e.BytesTransferred));
                    //giveback it at first.
                    ChannelConst.BuffAsyncStubPool.Giveback(stub);
                    channel.Disconnect();
                }

                #endregion
                break;

            //send complated event.
            case SocketAsyncOperation.Receive:
                #region Recv Completed.

                stub = (IFixedCacheStub <SocketBuffStub>)e.UserToken;
                TcpAsynDataRecevier recevier = (TcpAsynDataRecevier)stub.Tag;
                try { recevier.ProcessReceive(stub); }
                catch (System.Exception ex) { _tracing.Error(ex, null); }

                #endregion
                break;
            }
        }
Example #11
0
        public void DisconnectTest()
        {
            TcpTransportChannel     connectedChannel = null;
            TcpHostTransportChannel hostChannel      = new TcpHostTransportChannel(20004);

            Assert.IsTrue(hostChannel.Regist());
            hostChannel.ChannelCreated += delegate(object sender, LightSingleArgEventArgs <ITransportChannel> args)
            {
                connectedChannel = (TcpTransportChannel)args.Target;
            };
            TcpTransportChannel transportChannel = new TcpTransportChannel("127.0.0.1", 20004);

            Assert.IsTrue(transportChannel.CommunicationState == CommunicationStates.Unknown);
            transportChannel.Connect();
            Assert.IsTrue(transportChannel.IsConnected);
            Assert.IsTrue(transportChannel.CommunicationState == CommunicationStates.Opened);
            transportChannel.Disconnect();
            Assert.IsTrue(transportChannel.CommunicationState == CommunicationStates.Closed);
            Assert.IsTrue(hostChannel.UnRegist());
        }
        /// <summary>
        ///     准备与CSN之间的通信连接
        /// </summary>
        /// <exception cref="Exception">准备失败</exception>
        private void PrepareConnection()
        {
            if (_channel != null && _channel.IsConnected)
            {
                return;
            }
            int    offset = _csnAddress.LastIndexOf(':');
            string ip     = _csnAddress.Substring(0, offset);
            int    port   = int.Parse(_csnAddress.Substring(offset + 1, _csnAddress.Length - (offset + 1)));

            IPEndPoint        iep     = new IPEndPoint(IPAddress.Parse(ip), port);
            ITransportChannel channel = new TcpTransportChannel(iep);

            channel.Connect();
            if (!channel.IsConnected)
            {
                throw new Exception("Cannot connect to target CSN service. #address: " + iep);
            }
            _channel = new MessageTransportChannel <BaseMessage>((IRawTransportChannel)channel, _protocolStack);
            _channel.Disconnected    += ChannelDisconnected;
            _channel.ReceivedMessage += ChannelReceivedMessage;
        }
Example #13
0
        /// <summary>
        /// Creates a new UA-binary transport channel if requested. Null otherwise.
        /// </summary>
        /// <param name="configuration">The application configuration.</param>
        /// <param name="description">The description for the endpoint.</param>
        /// <param name="endpointConfiguration">The configuration to use with the endpoint.</param>
        /// <param name="clientCertificate">The client certificate.</param>
        /// <param name="clientCertificateChain">The client certificate chain.</param>
        /// <param name="messageContext">The message context to use when serializing the messages.</param>
        /// <returns></returns>
        public static ITransportChannel CreateUaBinaryChannel(
            ApplicationConfiguration configuration,
            EndpointDescription description,
            EndpointConfiguration endpointConfiguration,
            X509Certificate2 clientCertificate,
            X509Certificate2Collection clientCertificateChain,
            ServiceMessageContext messageContext)
        {
            bool useUaTcp = description.EndpointUrl.StartsWith(Utils.UriSchemeOpcTcp);
            bool useHttps = description.EndpointUrl.StartsWith(Utils.UriSchemeHttps);


            switch (description.TransportProfileUri)
            {
            case Profiles.UaTcpTransport:
            {
                useUaTcp = true;
                break;
            }

            case Profiles.HttpsBinaryTransport:
            {
                useHttps = true;
                break;
            }
            }

            // note: WCF channels are not supported
            if (!useUaTcp
#if !NO_HTTPS
                && !useHttps
#endif
                )
            {
                throw ServiceResultException.Create(
                          StatusCodes.BadProtocolVersionUnsupported,
                          "Unsupported transport profile\r\n");
            }

            // initialize the channel which will be created with the server.
            ITransportChannel channel = null;

            // create a UA-TCP channel.
            TransportChannelSettings settings = new TransportChannelSettings();

            settings.Description            = description;
            settings.Configuration          = endpointConfiguration;
            settings.ClientCertificate      = clientCertificate;
            settings.ClientCertificateChain = clientCertificateChain;

            if (description.ServerCertificate != null && description.ServerCertificate.Length > 0)
            {
                settings.ServerCertificate = Utils.ParseCertificateBlob(description.ServerCertificate);
            }

            if (configuration != null)
            {
                settings.CertificateValidator = configuration.CertificateValidator.GetChannelValidator();
            }

            settings.NamespaceUris = messageContext.NamespaceUris;
            settings.Factory       = messageContext.Factory;

            if (useUaTcp)
            {
                if (g_CustomTransportChannel != null)
                {
                    channel = g_CustomTransportChannel.Create();
                }
                else
                {
                    channel = new TcpTransportChannel();
                }
            }
            else if (useHttps)
            {
#if !NO_HTTPS
                channel = new HttpsTransportChannel();
#endif
            }

            channel.Initialize(new Uri(description.EndpointUrl), settings);
            channel.Open();

            return(channel);
        }
Example #14
0
        private void InnerHightSpeedSendTest(int destinationInstanceCount, int destinationMsgCount, int port)
        {
            int            msgRecvCount = 0, sendMsgCount = 0;
            int            previousMsgRecvCount = 0, previousSendMsgCount = 0;
            AutoResetEvent msgEvent = new AutoResetEvent(false);

            Console.Write("#Begining prepare Host channel resource...");
            TcpHostTransportChannel hostChannel = new TcpHostTransportChannel(port);

            Assert.IsTrue(hostChannel.Regist());
            hostChannel.ChannelCreated += delegate(object sender, LightSingleArgEventArgs <ITransportChannel> args)
            {
                MessageTransportChannel <MetadataContainer> msgChannel = new MessageTransportChannel <MetadataContainer>((IRawTransportChannel)args.Target, new MetadataProtocolStack());
                msgChannel.ReceivedMessage += delegate(object s, LightSingleArgEventArgs <List <MetadataContainer> > a)
                {
                    Interlocked.Add(ref msgRecvCount, a.Target.Count);
                };
            };
            Console.WriteLine("Done");
            Console.Write("#Begining prepare {0} numbers of TCP channel...", destinationInstanceCount);
            IList <TcpTransportChannel> clients = new List <TcpTransportChannel>();

            for (int i = 0; i < destinationInstanceCount; i++)
            {
                TcpTransportChannel transportChannel = new TcpTransportChannel("127.0.0.1", port);
                Assert.IsTrue(transportChannel.CommunicationState == CommunicationStates.Unknown);
                transportChannel.Connect();
                Assert.IsTrue(transportChannel.IsConnected);
                Assert.IsTrue(transportChannel.CommunicationState == CommunicationStates.Opened);
                clients.Add(transportChannel);
            }
            Console.WriteLine("Done");
            MetadataContainer container = new MetadataContainer();

            container.SetAttribute(0x00, new StringValueStored("Test-Name"));
            container.SetAttribute(0x01, new StringValueStored("Test-Value"));
            byte[] data = MetadataObjectEngine.ToBytes(container);
            Assert.IsNotNull(data);
            Console.WriteLine("#Sending message on those of transport channels...");
            ThreadPool.QueueUserWorkItem(delegate
            {
                while (true)
                {
                    previousMsgRecvCount = msgRecvCount;
                    previousSendMsgCount = sendMsgCount;
                    Thread.Sleep(1000);
                    if (destinationMsgCount != previousSendMsgCount || destinationMsgCount != previousMsgRecvCount)
                    {
                        Console.WriteLine();
                        Console.WriteLine("Send Count: {0}    <---{1} messages/per-second.", sendMsgCount, sendMsgCount - previousSendMsgCount);
                        Console.WriteLine("Recv Count: {0}    <---{1} messages/per-second.", msgRecvCount, msgRecvCount - previousMsgRecvCount);
                        Console.WriteLine();
                    }
                }
            });
            ThreadPool.QueueUserWorkItem(delegate
            {
                while (sendMsgCount != destinationMsgCount)
                {
                    for (int i = 0; i < clients.Count; i++)
                    {
                        clients[i].Send(data);
                        Interlocked.Increment(ref sendMsgCount);
                        if (sendMsgCount == destinationMsgCount)
                        {
                            break;
                        }
                    }
                    //Thread.Sleep(100);
                }
                msgEvent.Set();
            });
            msgEvent.WaitOne();
            Thread.Sleep(2000);
            Assert.IsTrue(sendMsgCount == destinationMsgCount);
            Assert.IsTrue(sendMsgCount == msgRecvCount);
            foreach (TcpTransportChannel clientChannel in clients)
            {
                clientChannel.Disconnect();
            }
            Thread.Sleep(2000);
        }
Example #15
0
        public void SendMessageTest()
        {
            ITransportChannel       connectedChannel = null;
            AutoResetEvent          resetEvent       = new AutoResetEvent(false);
            AutoResetEvent          msgEvent         = new AutoResetEvent(false);
            AutoResetEvent          channelEvent     = new AutoResetEvent(false);
            TcpHostTransportChannel hostChannel      = new TcpHostTransportChannel(20005);

            Assert.IsTrue(hostChannel.Regist());
            hostChannel.ChannelCreated += delegate(object sender, LightSingleArgEventArgs <ITransportChannel> args)
            {
                connectedChannel = args.Target;
                channelEvent.Set();
            };
            TcpTransportChannel transportChannel = new TcpTransportChannel("127.0.0.1", 20005);

            Assert.IsTrue(transportChannel.CommunicationState == CommunicationStates.Unknown);
            transportChannel.Connect();
            if (!channelEvent.WaitOne(2000))
            {
                throw new System.Exception("#Cannot passed channel be connect test.");
            }
            Assert.IsNotNull(connectedChannel);
            Assert.IsTrue(connectedChannel.IsConnected);
            Assert.IsTrue(transportChannel.IsConnected);
            Assert.IsTrue(transportChannel.CommunicationState == CommunicationStates.Opened);
            MetadataContainer msg = null;
            IMessageTransportChannel <MetadataContainer> msgChannel = new MessageTransportChannel <MetadataContainer>((IRawTransportChannel)connectedChannel, new MetadataProtocolStack());

            msgChannel.ReceivedMessage += delegate(object sender, LightSingleArgEventArgs <List <MetadataContainer> > args)
            {
                msg = args.Target[0];
                msgEvent.Set();
            };
            MetadataContainer container = new MetadataContainer();

            container.SetAttribute(0x00, new StringValueStored("Test-Name"));
            container.SetAttribute(0x01, new StringValueStored("Test-Value"));
            byte[] data = MetadataObjectEngine.ToBytes(container);
            Assert.IsNotNull(data);
            int sendCount = transportChannel.Send(data);

            Assert.IsTrue(sendCount == data.Length || sendCount == 1);
            if (!msgEvent.WaitOne(2000))
            {
                throw new System.Exception("#Cannot passed message channel receive test.");
            }
            Assert.IsNotNull(msg);
            Console.WriteLine(msg);

            msgChannel.Disconnected += delegate { resetEvent.Set(); };
            transportChannel.Disconnect();
            if (!resetEvent.WaitOne(10000))
            {
                throw new System.Exception("#Cannot passed transport channel disconnect test.");
            }
            Assert.IsTrue(transportChannel.CommunicationState == CommunicationStates.Closed);
            Thread.Sleep(2000);
            Assert.IsTrue(!connectedChannel.IsConnected);
            Assert.IsTrue(hostChannel.UnRegist());
        }
 /// <summary>
 ///     ����һ���µ����Ӵ�����
 /// </summary>
 /// <param name="iep">Զ���ս���ַ</param>
 /// <param name="protocolStack">Э��ջ</param>
 /// <param name="transactionManager">���������</param>
 /// <returns>����޷����ӵ�Զ�̵�ַ���򷵻�null.</returns>
 public static IThriftConnectionAgent Create(IPEndPoint iep, IProtocolStack<ThriftMessage> protocolStack, ThriftMessageTransactionManager transactionManager)
 {
     if (iep == null) throw new ArgumentNullException("iep");
     if (protocolStack == null) throw new ArgumentNullException("protocolStack");
     if (transactionManager == null) throw new ArgumentNullException("transactionManager");
     ITransportChannel transportChannel = new TcpTransportChannel(iep);
     transportChannel.Connect();
     if (!transportChannel.IsConnected) return null;
     IMessageTransportChannel<ThriftMessage> msgChannel = new MessageTransportChannel<ThriftMessage>((IRawTransportChannel)transportChannel, protocolStack, new ThriftProtocolSegmentDataParser((ThriftProtocolStack) protocolStack));
     return new ThriftConnectionAgent(msgChannel, transactionManager);
 }