Example #1
0
        private TTransport MakeTransport(URL url, TConfiguration configuration)
        {
            var ipaddress = IPAddress.Loopback;

            if (!NetUtil.IsAnyHost(url.Host) && !NetUtil.IsLocalHost(url.Host))
            {
                ipaddress = IPAddress.Parse(url.Host);
            }
            // construct endpoint transport
            TTransport transport         = null;
            Transport  selectedTransport = GetTransport(url);
            {
                switch (selectedTransport)
                {
                case Transport.Tcp:
                    transport = new TSocketTransport(ipaddress, url.Port, configuration);
                    break;

                case Transport.NamedPipe:
                    transport = new TNamedPipeTransport(".test", configuration);
                    break;

                case Transport.Http:
                    transport = new THttpTransport(new Uri($"http://{url.Host}:{url.Port}"), configuration);
                    break;

                case Transport.TcpTls:
                    transport = new TTlsSocketTransport(ipaddress, url.Port, configuration,
                                                        GetCertificate(), CertValidator, LocalCertificateSelectionCallback);
                    break;

                default:
                    Console.WriteLine("unhandled case");
                    break;
                }
            }

            // optionally add layered transport(s)
            Buffering selectedBuffering = GetBuffering(url);

            switch (selectedBuffering)
            {
            case Buffering.Buffered:
                transport = new TBufferedTransport(transport);
                break;

            case Buffering.Framed:
                transport = new TFramedTransport(transport);
                break;

            default:     // layered transport(s) are optional
                if (selectedBuffering != Buffering.None)
                {
                    Console.WriteLine("unhandled case");
                }
                break;
            }

            return(transport);
        }
Example #2
0
        protected virtual I ConnectClient(bool silent = false)
        {
            const int TIMEOUT = 15 * 1000;

            try
            {
                // try to connect this server using timeout
                if (!silent)
                {
                    Console.Write("Testing for server at {0}:{1} ... ", Server, Port);
                }
                using (var test = new TSocket(Server, Port, TIMEOUT))
                    test.Open();

                if (!silent)
                {
                    Console.WriteLine("OK", Server, Port);
                }
                var trans = new TFramedTransport(new TSocket(Server, Port, TIMEOUT));
                var proto = new TBinaryProtocol(trans);
                var mplex = new TMultiplexedProtocol(proto, MultiplexName());

                trans.Open();
                return(ClientFactory(mplex));
            }
            catch (Exception e)
            {
                Console.WriteLine("Machine {0} port {1}: {2}", Server, Port, e.Message);
            }

            throw new Exception(string.Format("{0}: Can't reach a server at {1}:{2} ... ", DateTime.UtcNow, Server, Port));
        }
Example #3
0
        static void Main(string[] args)
        {
            // Initialize log4net
            l4n.Config.XmlConfigurator.Configure();

            // Create log
            var log = new LogEntry();

            log.Category = "Program";
            log.Message  = "This is a test error message from the program";

            // Connect
            var socket       = new TSocket("192.168.1.144", 65510, 300);
            var transport    = new TFramedTransport(socket);
            var protocol     = new TBinaryProtocol(transport, false, false);
            var scribeClient = new scribe.Client(protocol);

            transport.Open();

            // Send
            var logs = new List <LogEntry>();

            logs.Add(log);
            var result = scribeClient.Log(logs);

            // Close
            transport.Close();

            // use log4net to log
            var logger = l4n.LogManager.GetLogger("ScribeAppender.Test.Program");

            logger.Debug("This is a test error message from the logger");
        }
Example #4
0
        /// <summary>
        /// Retrives the correct Thrift transport type based on the value in <see cref="Transport"/>.
        /// </summary>
        /// <returns>If <see cref="Transport"/> is <code>namedpipe</code> then a <see cref="TNamedPipeClientTransport"/> is used.  For all other values
        /// a <see cref="TSocket"/> is returned.  Depending on the value of <see cref="Framed"/> and <see cref="Buffered"/>, appropriate wrappers will be placed
        /// around the transport.
        /// </returns>
        public TTransport GetThriftTransport()
        {
            TTransport transport;

            switch (Transport)
            {
            case "namedpipe":
                transport = new TNamedPipeClientTransport(ServiceHost, NamedPipeName);
                break;

            //                case "socket":
            default:
                transport = new TSocket(ServiceHost, ServicePort);
                break;
            }

            if (Framed)
            {
                transport = new TFramedTransport(transport);
            }

            if (Buffered)
            {
                transport = new TBufferedTransport((TStreamTransport)transport, BufferSize);
            }

            return(transport);
        }
Example #5
0
        public static void FistTest()
        {
            Console.WriteLine("Thrift2 Demo");
            Console.WriteLine("This demo assumes you have a table called \"example\" with a column family called \"family1\"");

            String host    = "hserver";
            int    port    = 9090;
            int    timeout = 10000;
            var    framed  = false;

            TTransport transport = new TSocket(host, port, timeout);

            if (framed)
            {
                transport = new TFramedTransport(transport);
            }
            TProtocol protocol = new TBinaryProtocol(transport);

            // This is our thrift client.
            THBaseService.Iface client = new THBaseService.Client(protocol);

            // open the transport
            transport.Open();

            var table = "t1".ToBytes();

            TPut put = new TPut();

            put.Row = ("row1".ToBytes());

            for (var i = 0; i < 1000; i++)
            {
                TColumnValue columnValue = new TColumnValue();
                columnValue.Family    = ("f1".ToBytes());
                columnValue.Qualifier = ("qualifier" + i).ToBytes();
                columnValue.Value     = ("value" + i).ToBytes();
                List <TColumnValue> columnValues = new List <TColumnValue>();
                columnValues.Add(columnValue);
                put.ColumnValues = columnValues;

                client.put(table, put);
            }

            TGet get = new TGet();

            get.Row = ("row1".ToBytes());

            TResult result = client.get(table, get);

            Console.WriteLine("row = " + result.Row.ToStr());
            foreach (TColumnValue resultColumnValue in result.ColumnValues)
            {
                Console.WriteLine("family = " + resultColumnValue.Family.ToStr());
                Console.WriteLine("qualifier = " + resultColumnValue.Qualifier.ToStr());
                Console.WriteLine("value = " + resultColumnValue.Value.ToStr());
                Console.WriteLine("timestamp = " + resultColumnValue.Timestamp);
            }

            transport.Close();
        }
Example #6
0
 public ThriftClient()
 {
     transport = new TSocket("192.168.9.203", 7911);
     tframed   = new TFramedTransport(transport);
     protocol  = new TCompactProtocol(tframed);
     client    = new MLtynHost.Client(protocol);
 }
Example #7
0
        /// <summary>
        /// 初始化Thrift远程服务
        /// </summary>
        public static void InitThriftServer()
        {
            m_initThriftServerEvent.WaitOne();
            List <TTransport> transportList = m_transportList;

            if (transportList == null)
            {
                transportList = new List <TTransport>();
            }

            ReleaseThriftServer(transportList);

            IServerInfo serverInfo = ZKManager.Client.GetAliveLogServer(m_logToServer);

            //IServerInfo serverInfo = ServerManager.Get(m_logToServer);
            m_localLog.Error(string.Format("serverip: {0}, port: {1}", serverInfo.Address, serverInfo.Port));
            if (serverInfo != null)
            {
                for (int i = 0; i < m_pollingSize; i++)
                {
                    TFramedTransport transport = new TFramedTransport(new TSocket(serverInfo.Address, serverInfo.Port, serverInfo.Timeout));
                    transportList.Add(transport);
                }
            }
            m_transportList = transportList;
        }
Example #8
0
        protected override async Task <TTransport> AcceptImplementationAsync(CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(await Task.FromCanceled <TTransport>(cancellationToken));
            }

            if (_server == null)
            {
                throw new TTransportException(TTransportException.ExceptionType.NotOpen, "No underlying server socket.");
            }

            try
            {
                TTransport tSocketTransport = null;
                var        tcpClient        = await _server.AcceptTcpClientAsync();

                try
                {
                    tSocketTransport = new TSocketTransport(tcpClient)
                    {
                        Timeout = _clientTimeout
                    };

                    switch (_buffering)
                    {
                    case Buffering.BufferedTransport:
                        tSocketTransport = new TBufferedTransport(tSocketTransport);
                        break;

                    case Buffering.FramedTransport:
                        tSocketTransport = new TFramedTransport(tSocketTransport);
                        break;

                    default:
                        Debug.Assert(_buffering == Buffering.None);
                        break;
                    }

                    return(tSocketTransport);
                }
                catch (Exception)
                {
                    if (tSocketTransport != null)
                    {
                        tSocketTransport.Dispose();
                    }
                    else //  Otherwise, clean it up ourselves.
                    {
                        ((IDisposable)tcpClient).Dispose();
                    }

                    throw;
                }
            }
            catch (Exception ex)
            {
                throw new TTransportException(ex.ToString());
            }
        }
Example #9
0
        public static void TestClient()
        {
            TTransport           transport = new TFramedTransport(new TSocket("localhost", 9090));
            TProtocol            protocol  = new TBinaryProtocol(transport);
            TMultiplexedProtocol mp        = new TMultiplexedProtocol(protocol, "search_service");

            SearchService.Client client = new SearchService.Client(mp);

            transport.Open();

            SearchRequest req = new SearchRequest();

            req.FileMask     = "*.bat";
            req.StartPath    = "c:\\";
            req.IgnoreErrors = true;
            var result = client.Search(req);

            Debug.WriteLine("P10");

            client.Delay1(2000);
            client.Delay2(1000);

            Task t1 = Task.Factory.StartNew(() => { Debug.WriteLine("T1:begin"); client.Delay1(2000); Debug.WriteLine("T1:end"); });
            Task t2 = Task.Factory.StartNew(() => { Debug.WriteLine("T2:begin"); client.Delay2(1000); Debug.WriteLine("T2:end"); });

            Debug.WriteLine("P20");

            t2.Wait();

            Debug.WriteLine("P30");

            t1.Wait();

            Debug.WriteLine("P40");
        }
Example #10
0
        public static void userFilter()
        {
            String host    = "hserver";
            int    port    = 9090;
            int    timeout = 10000;
            var    framed  = false;

            TTransport transport = new TSocket(host, port, timeout);

            if (framed)
            {
                transport = new TFramedTransport(transport);
            }
            TProtocol protocol = new TBinaryProtocol(transport);

            // This is our thrift client.
            THBaseService.Iface client = new THBaseService.Client(protocol);

            // open the transport
            transport.Open();



            transport.Close();
        }
        private TTransport CreateInstance()
        {
            TTransport transport = new TFramedTransport(new TSocket(Conf.TSeriviceHost, Conf.TServicePort));

            transport.Open();
            return(transport);
        }
Example #12
0
        protected RemoteController.Client CreateRemoteController()
        {
            TTransport transport = new TFramedTransport(new TSocket("localhost", 9701));

            transport.Open();
            TProtocol protocol = new TBinaryProtocol(transport);

            return(new ThreadSafeRemoteController(protocol));
        }
Example #13
0
        public async Task <Client> create_and_open(bool enableRPCCompression)
        {
            TcpClient tcp_client = new TcpClient(this.host, this.port);

            TSIService.Client client;
            long sessionId, statementId;
            var  transport = new TFramedTransport(new TSocketTransport(tcp_client, null));

            if (!transport.IsOpen)
            {
                try{
                    await transport.OpenAsync(new CancellationToken());
                }
                catch (TTransportException) {
                    throw;
                }
            }
            if (enableRPCCompression)
            {
                client = new TSIService.Client(new TCompactProtocol(transport));
            }
            else
            {
                client = new TSIService.Client(new TBinaryProtocol(transport));
            }
            var open_req = new TSOpenSessionReq(protocol_version, zoneId);

            open_req.Username = username;
            open_req.Password = password;
            try{
                var open_resp = await client.openSessionAsync(open_req);

                if (open_resp.ServerProtocolVersion != protocol_version)
                {
                    var message = String.Format("Protocol Differ, Client version is {0} but Server version is {1}", protocol_version, open_resp.ServerProtocolVersion);
                    throw new TException(message, null);
                }
                if (open_resp.ServerProtocolVersion == 0)
                {
                    throw new TException("Protocol not supported", null);
                }
                sessionId   = open_resp.SessionId;
                statementId = await client.requestStatementIdAsync(sessionId);
            }
            catch (Exception) {
                transport.Close();
                throw;
            }
            is_close = false;
            var return_client = new Client();

            return_client.client      = client;
            return_client.sessionId   = sessionId;
            return_client.statementId = statementId;
            return_client.transport   = transport;
            return(return_client);
        }
Example #14
0
        private static TTransport GetTransport(string[] args)
        {
            TTransport transport = new TSocketTransport(IPAddress.Loopback, 9090, Configuration);

            // construct endpoint transport
            var transportArg = args.FirstOrDefault(x => x.StartsWith("-tr"))?.Split(':')?[1];

            if (Enum.TryParse(transportArg, true, out Transport selectedTransport))
            {
                switch (selectedTransport)
                {
                case Transport.Tcp:
                    transport = new TSocketTransport(IPAddress.Loopback, 9090, Configuration);
                    break;

                case Transport.NamedPipe:
                    transport = new TNamedPipeTransport(".test", Configuration);
                    break;

                case Transport.Http:
                    transport = new THttpTransport(new Uri("http://localhost:9090"), Configuration);
                    break;

                case Transport.TcpTls:
                    transport = new TTlsSocketTransport(IPAddress.Loopback, 9090, Configuration,
                                                        GetCertificate(), CertValidator, LocalCertificateSelectionCallback);
                    break;

                default:
                    Debug.Assert(false, "unhandled case");
                    break;
                }
            }

            // optionally add layered transport(s)
            var bufferingArg = args.FirstOrDefault(x => x.StartsWith("-bf"))?.Split(':')?[1];

            if (Enum.TryParse <Buffering>(bufferingArg, out var selectedBuffering))
            {
                switch (selectedBuffering)
                {
                case Buffering.Buffered:
                    transport = new TBufferedTransport(transport);
                    break;

                case Buffering.Framed:
                    transport = new TFramedTransport(transport);
                    break;

                default:     // layered transport(s) are optional
                    Debug.Assert(selectedBuffering == Buffering.None, "unhandled case");
                    break;
                }
            }

            return(transport);
        }
Example #15
0
        public static Cassandra.Client GetWebClient()
        {
            var transport = new TFramedTransport(new TSocket("localhost", 9160));
            var client    = new Cassandra.Client(new TBinaryProtocol(transport));

            transport.Open();
            client.set_keyspace(_keySpace);
            return(client);
        }
Example #16
0
            public TTransport CreateTransport()
            {
                // endpoint transport
                TTransport trans = null;

                switch (transport)
                {
                case TransportChoice.Http:
                    Debug.Assert(url != null);
                    trans = new THttpTransport(new Uri(url), Configuration);
                    break;

                case TransportChoice.NamedPipe:
                    Debug.Assert(pipe != null);
                    trans = new TNamedPipeTransport(pipe, Configuration);
                    break;

                case TransportChoice.TlsSocket:
                    var cert = GetClientCert();
                    if (cert == null || !cert.HasPrivateKey)
                    {
                        throw new InvalidOperationException("Certificate doesn't contain private key");
                    }

                    trans = new TTlsSocketTransport(host, port, Configuration, 0,
                                                    cert,
                                                    (sender, certificate, chain, errors) => true,
                                                    null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12);
                    break;

                case TransportChoice.Socket:
                default:
                    trans = new TSocketTransport(host, port, Configuration);
                    break;
                }


                // layered transport
                switch (layered)
                {
                case LayeredChoice.Buffered:
                    trans = new TBufferedTransport(trans);
                    break;

                case LayeredChoice.Framed:
                    trans = new TFramedTransport(trans);
                    break;

                default:
                    Debug.Assert(layered == LayeredChoice.None);
                    break;
                }

                return(trans);
            }
Example #17
0
        public static Cassandra.Client GetClient(string keyspace, ref TTransport transport)
        {
            TTransport frameTransport = new TFramedTransport(new TSocket("localhost", 9160));
            TProtocol  frameProtocol  = new TBinaryProtocol(frameTransport);
            var        client         = new Cassandra.Client(frameProtocol, frameProtocol);

            frameTransport.Open();
            client.set_keyspace(keyspace);
            transport = frameTransport;
            return(client);
        }
Example #18
0
        public override void Open(string hostname)
        {
            base.Open(hostname);

            TTransport transport = new TFramedTransport(new TSocket(hostname, 9160));
            TProtocol  protocol  = new TBinaryProtocol(transport);

            _client = new Cassandra.Client(protocol);

            transport.Open();
        }
Example #19
0
        public ThriftClient(string host, int port)
        {
            if (host == null)
            {
                throw new ArgumentNullException("host");
            }

            _transport = new TFramedTransport(new TSocket(host, port));
            TProtocol protocol = new TCompactProtocol(_transport);

            _client = new ThriftSourceProtocol.Client(protocol);
            _transport.Open();
        }
Example #20
0
        private static TTransport MakeTransport(string[] args)
        {
            // construct endpoint transport
            TTransport transport         = null;
            Transport  selectedTransport = GetTransport(args);
            {
                switch (selectedTransport)
                {
                case Transport.Tcp:
                    transport = new TSocketTransport(IPAddress.Loopback, 9090, Configuration);
                    break;

                case Transport.NamedPipe:
                    transport = new TNamedPipeTransport(".test", Configuration);
                    break;

                case Transport.Http:
                    transport = new THttpTransport(new Uri("http://localhost:9090"), Configuration);
                    break;

                case Transport.TcpTls:
                    transport = new TTlsSocketTransport(IPAddress.Loopback, 9090, Configuration,
                                                        GetCertificate(), CertValidator, LocalCertificateSelectionCallback);
                    break;

                default:
                    Debug.Assert(false, "unhandled case");
                    break;
                }
            }

            // optionally add layered transport(s)
            Buffering selectedBuffering = GetBuffering(args);

            switch (selectedBuffering)
            {
            case Buffering.Buffered:
                transport = new TBufferedTransport(transport);
                break;

            case Buffering.Framed:
                transport = new TFramedTransport(transport);
                break;

            default:     // layered transport(s) are optional
                Debug.Assert(selectedBuffering == Buffering.None, "unhandled case");
                break;
            }

            return(transport);
        }
Example #21
0
        /// <summary>
        /// create an instance
        /// </summary>
        /// <returns></returns>
        private TTransport CreateInstance()
        {
            TSocket socket = new TSocket(config.Host, config.Port);

            if (config.Timeout > 0)
            {
                socket.Timeout = config.Timeout;
            }

            TTransport transport = new TFramedTransport(socket);

            transport.Open();
            return(transport);
        }
Example #22
0
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _transport.Close();
                    _transport.Dispose();
                    _transport = null;
                }
            }

            _disposed = true;
        }
Example #23
0
 public static void Main(string[] args)
 {
     try
     {
         //Accumulo details
         String accumuloProxyServerIP   = "192.168.1.44";    //IP
         int    accumuloProxyServerPort = 42424;             //Port Number
         //Connect to Accumulo proxy server
         TTransport transport = new TSocket(accumuloProxyServerIP, accumuloProxyServerPort);
         transport = new TFramedTransport(transport);
         TCompactProtocol protocol = new TCompactProtocol(transport);
         transport.Open();
         String principal = "root";                                     //Application ID
         Dictionary <string, string> passwd = new Dictionary <string, string>();
         passwd.Add("password", "xxxxx");                               //Password
         AccumuloProxy.Client client = new AccumuloProxy.Client(protocol);
         byte[] loginToken           = client.login(principal, passwd); //Login token
         //{{
         //Read a range of rows from Accumulo
         var   bScanner = new BatchScanOptions();
         Range range    = new Range();
         range.Start     = new Key();
         range.Start.Row = GetBytes("d001");
         //Need the \0 only if you need to get a single row back
         //Otherwise, its not needed
         range.Stop      = new Key();
         range.Stop.Row  = GetBytes("d001\0");
         bScanner.Ranges = new List <Range>();
         bScanner.Ranges.Add(range);
         String scanId = client.createBatchScanner(loginToken, "departments", bScanner);
         var    more   = true;
         while (more)
         {
             var scan = client.nextK(scanId, 10);
             more = scan.More;
             foreach (var entry in scan.Results)
             {
                 Console.WriteLine("Row = " + GetString(entry.Key.Row));
                 Console.WriteLine("{0} {1}:{2} [{3}]  {4}    {5}", GetString(entry.Key.Row), GetString(entry.Key.ColFamily), GetString(entry.Key.ColQualifier), GetString(entry.Key.ColVisibility), GetString(entry.Value), (long)entry.Key.Timestamp);
             }
         }
         client.closeScanner(scanId);
         client.Dispose();
         transport.Close();
     }catch (Exception e)
     {
         Console.WriteLine(e);
     }
     //}}
 }
Example #24
0
            public TTransport CreateTransport()
            {
                if (url == null)
                {
                    // endpoint transport
                    TTransport trans = null;
                    if (pipe != null)
                    {
                        trans = new TNamedPipeClientTransport(pipe);
                    }
                    else
                    {
                        if (encrypted)
                        {
                            string          certPath = "../keys/client.p12";
                            X509Certificate cert     = new X509Certificate2(certPath, "thrift");
                            trans = new TTLSSocket(host, port, 0, cert,
                                                   (o, c, chain, errors) => true,
                                                   null, SslProtocols.Tls);
                        }
                        else
                        {
                            trans = new TSocket(host, port);
                        }
                    }

                    // layered transport
                    if (buffered)
                    {
                        trans = new TBufferedTransport(trans);
                    }
                    if (framed)
                    {
                        trans = new TFramedTransport(trans);
                    }

                    if (_isFirstTransport)
                    {
                        //ensure proper open/close of transport
                        trans.Open();
                        trans.Close();
                        _isFirstTransport = false;
                    }
                    return(trans);
                }
                else
                {
                    return(new THttpClient(new Uri(url)));
                }
            }
Example #25
0
        public ScribeSpanDispatcher(string hostname, int port)
        {
            _hostname = hostname;
            _port     = port;

            _tcpClient = new TcpClient
            {
                NoDelay = true
            };
            _tcpClient.ConnectAsync(hostname, port).RunSynchronously();

            _frame         = new TFramedTransport(new TTcpClientTransport(_tcpClient));
            _scribeService = new ScribeService(new ThriftProtocol(_frame));
        }
Example #26
0
            public TTransport CreateTransport()
            {
                if (url == null)
                {
                    // endpoint transport
                    TTransport trans = null;

                    if (pipe != null)
                    {
                        trans = new TNamedPipeTransport(pipe);
                    }
                    else
                    {
                        if (encrypted)
                        {
                            var cert = GetClientCert();

                            if (cert == null || !cert.HasPrivateKey)
                            {
                                throw new InvalidOperationException("Certificate doesn't contain private key");
                            }

                            trans = new TTlsSocketTransport(host, port, 0, cert,
                                                            (sender, certificate, chain, errors) => true,
                                                            null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12);
                        }
                        else
                        {
                            trans = new TSocketTransport(host, port);
                        }
                    }

                    // layered transport
                    if (buffered)
                    {
                        trans = new TBufferedTransport(trans);
                    }

                    if (framed)
                    {
                        trans = new TFramedTransport(trans);
                    }

                    return(trans);
                }

                return(new THttpTransport(new Uri(url), null));
            }
        protected override async Task <TTransport> AcceptImplementationAsync(CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(await Task.FromCanceled <TTransport>(cancellationToken));
            }

            if (_server == null)
            {
                throw new TTransportException(TTransportException.ExceptionType.NotOpen, "No underlying server socket.");
            }

            try
            {
                var client = await _server.AcceptTcpClientAsync();

                client.SendTimeout = client.ReceiveTimeout = _clientTimeout;

                //wrap the client in an SSL Socket passing in the SSL cert
                var tTlsSocket = new TTlsSocketTransport(client, _serverCertificate, true, _clientCertValidator,
                                                         _localCertificateSelectionCallback, _sslProtocols);

                await tTlsSocket.SetupTlsAsync();

                TTransport trans = tTlsSocket;

                switch (_buffering)
                {
                case Buffering.BufferedTransport:
                    trans = new TBufferedTransport(trans);
                    break;

                case Buffering.FramedTransport:
                    trans = new TFramedTransport(trans);
                    break;

                default:
                    Debug.Assert(_buffering == Buffering.None);
                    break;
                }

                return(trans);
            }
            catch (Exception ex)
            {
                throw new TTransportException(ex.ToString());
            }
        }
Example #28
0
        static void Main()
        {
            using (var consul = new Consul.ConsulClient(c =>
            {
                c.Address = new Uri("http://127.0.0.1:8500");
            }))
            {
                //获取在Consul注册的全部服务
                var services = consul.Agent.Services().Result.Response;

                foreach (var s in services.Values)
                {
                    Console.WriteLine($"ID={s.ID},Service={s.Service},Addr={s.Address},Port={s.Port}");
                }
                var service = consul.Agent.Services().Result.Response.Values.Where(
                    p => p.Service.Equals("test-server-rpc", StringComparison.OrdinalIgnoreCase)).First();


                /*
                 * thrift的使用中一般是一个Server对应一个Processor和一个Transport,如果有多个服务的话,那必须要启动多个Server,
                 * 占用多个端口,这种方式显然不是我们想要的,所以thrift为我们提供了复用端口的方式,
                 * 通过监听一个端口就可以提供多种服务,
                 * 这种方式需要用到两个类:TMultiplexedProcessor和TMultiplexedProtocol。
                 *
                 */
                IPAddress ip = IPAddress.Parse(service.Address);

                using (TcpClient tcpClient = new System.Net.Sockets.TcpClient())
                {
                    tcpClient.Connect(ip, service.Port);
                    using (TTransport transport = new TSocket(tcpClient))
                    {
                        TTransport frameTransport = new TFramedTransport(transport);

                        TProtocol protocol = new TCompactProtocol(frameTransport);
                        //如果服务端使用TMultiplexedProcessor接收处理,客户端必须用TMultiplexedProtocol并且指定serviceName和服务端的一致
                        TMultiplexedProtocol multiplexedProtocol = new TMultiplexedProtocol(protocol, service.Service + "$com.msunsoft.service.calculator$2.0");
                        Client client = new Client(multiplexedProtocol);
                        //transport.Open();
                        Console.WriteLine(client.add(1, 2));
                    }
                }
            }


            Console.ReadLine();
        }
Example #29
0
        public ThriftConnection(int timeout, IPEndPoint ipEndPoint, string keyspaceName, ILog logger)
        {
            isDisposed        = false;
            isAlive           = true;
            this.ipEndPoint   = ipEndPoint;
            this.keyspaceName = keyspaceName;
            this.logger       = logger;
            var address = ipEndPoint.Address.ToString();
            var port    = ipEndPoint.Port;
            var tsocket = timeout == 0 ? new TSocket(address, port) : new TSocket(address, port, timeout);
            var socket  = tsocket.TcpClient.Client;

            socket.NoDelay = true;
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
            var transport = new TFramedTransport(tsocket);

            cassandraClient   = new Apache.Cassandra.Cassandra.Client(new TBinaryProtocol(transport));
            creationTimestamp = Timestamp.Now;
            OpenTransport();
        }
        public async Task <ITransportClient> CreateClientAsync(EndPoint endPoint)
        {
            try
            {
                var ipEndPoint      = endPoint as IPEndPoint;
                var transport       = new TSocketTransport(ipEndPoint.Address.ToString(), ipEndPoint.Port);
                var tran            = new TFramedTransport(transport);
                var protocol        = new TBinaryProtocol(tran);
                var mp              = new TMultiplexedProtocol(protocol, "thrift.surging");
                var messageListener = new MessageListener();
                var messageSender   = new ThriftMessageClientSender(_transportMessageEncoder, protocol);
                var result          = new TThriftClient(protocol, messageSender, messageListener, new ChannelHandler(_transportMessageDecoder, messageListener, messageSender), _app);
                await result.OpenTransportAsync();

                return(result);
            }
            catch
            {
                throw;
            }
        }