예제 #1
0
    public RpcClient()
    {
        //var factory = new ConnectionFactory() { HostName = "localhost" };
        var factory = new ConnectionFactory()
        {
            HostName = "192.168.0.25", Port = 5672, UserName = "******", Password = "******"
        };

        connection = factory.CreateConnection();
        channel    = connection.CreateModel();

        var args2 = new Dictionary <string, object>();

        args2.Add("x-message-ttl", 1000);

        replyQueueName = channel.QueueDeclare("myqueue", false, false, false, args2).QueueName;
        consumer       = new EventingBasicConsumer(channel);

        /*  props = channel.CreateBasicProperties();
         * var correlationId = Guid.NewGuid().ToString();
         * props.CorrelationId = correlationId;
         * props.ReplyTo = replyQueueName;
         *
         * props.ContentType = "text/plain";
         * props.DeliveryMode = 2;
         * props.Expiration = "2000";
         */

        SimpleRpcClient client = new SimpleRpcClient(channel, "", "", "rpc_queue");

        client.TimeoutMilliseconds = 5000; // 5 sec. defaults to infinity

        //var message1 = Encoding.UTF8.GetBytes("1");

        //client.TimedOut += RpcTimedOutHandler;
        //client.Disconnected += RpcDisconnectedHandler;


        //byte[] replyMessageBytes1 = client.Call(message1);
        //Console.WriteLine(" [.] Got '{0}'", Encoding.UTF8.GetString(replyMessageBytes1));

        for (int i = 0; i < 100; i++)
        {
            var    message           = Encoding.UTF8.GetBytes(i.ToString());
            byte[] replyMessageBytes = client.Call(message);

            Console.WriteLine(" [.] Got '{0}'", Encoding.UTF8.GetString(replyMessageBytes));
        }

        /*consumer.Received += (model, ea) =>
         * {
         *  var body = ea.Body;
         *  var response = Encoding.UTF8.GetString(body);
         *  if (ea.BasicProperties.CorrelationId == correlationId)
         *  {
         *      respQueue.Add(response);
         *  }
         * };*/
    }
예제 #2
0
        static void Main(string[] args)
        {
            ConnectionFactory cf = new ConnectionFactory();
            var con   = cf.CreateConnection();
            var model = con.CreateModel();

            SimpleRpcClient client = new SimpleRpcClient(model);
        }
예제 #3
0
        public void RPCClient(IConnection con, IModel channel)
        {
            byte[]          requestMessageBytes = null;
            SimpleRpcClient client = new SimpleRpcClient(channel, "");

            //SimpleRpcServer server = new SimpleRpcServer();
            client.TimedOut     += Client_TimedOut;
            client.Disconnected += Client_Disconnected;
            byte[] replyMessageBytes = client.Call(requestMessageBytes);
        }
예제 #4
0
        public static Web3 GetWeb3UsingHttpClientFactory(IAccount account = null)
        {
            var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();

            var httpClientFactory = serviceProvider.GetService <IHttpClientFactory>();

            var client = httpClientFactory.CreateClient();

            var rpc = new SimpleRpcClient(new Uri("http://localhost:8545"), client);

            return(account != null ? new Web3(account, rpc) : new Web3(rpc));
        }
예제 #5
0
        public NesterQueueRPCClient(string exchange,
                                    string routingKey, IConnection connection,
                                    int timeoutMilliseconds = 5000)
        {
            _exchange = exchange;
            _model    = connection.CreateModel();

            _client = new SimpleRpcClient(_model,
                                          exchange, "topic", routingKey);
            _client.TimeoutMilliseconds = timeoutMilliseconds;

            SetDefaults();
        }
예제 #6
0
        protected T Proxy <T>(string methodName, params object[] parameters)
        {
            using (var channel = m_Connection.CreateModel())
            {
                string rpcQueueName = $"{m_BrokerQueueId}.{m_ClassName}.{methodName}";

                channel.QueueDeclare(queue: rpcQueueName,
                                     durable: false,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);

                SimpleRpcClient client = new SimpleRpcClient(channel, "", "direct", rpcQueueName);
                client.TimeoutMilliseconds = m_TimeOut;

                var corrId             = Guid.NewGuid().ToString();
                IBasicProperties props = channel.CreateBasicProperties();
                props.Persistent    = false;
                props.ReplyTo       = channel.QueueDeclare(queue: $"rpc.{rpcQueueName}.{corrId}").QueueName;
                props.CorrelationId = corrId;

                parameters = parameters ?? new object[0];
                byte[] messageBytes = parameters.SerializeToByteArray();

                var response = client.Call(props, messageBytes);

                if (response == null)
                {
                    return(default(T));
                }

                byte[] replyMessageBytes = response.Body;

                if (replyMessageBytes == null || replyMessageBytes.Length <= 0)
                {
                    return(default(T));
                }

                try
                {
                    T result = replyMessageBytes.Deserialize <T>();
                    return(result);
                }
                catch (Exception ex)
                {
                    //TODO : log ex
                }

                return(default(T));
            }
        }
 static void Main(string[] args)
 {
     ConnectionFactory factory = new ConnectionFactory()
     {
         HostName = "192.168.23.146",
         UserName = "******",
         Password = "******",
     };
     //第一步:创建connection
     var connection = factory.CreateConnection();
     //第二步:创建一个channel
     var             channel = connection.CreateModel();
     SimpleRpcClient client  = new SimpleRpcClient(channel, string.Empty, ExchangeType.Direct, "rpc_queue");
     var             bytes   = client.Call(Encoding.UTF8.GetBytes("hello world!!!!"));
     var             result  = Encoding.UTF8.GetString(bytes);
 }
예제 #8
0
 public static void RPCClient(ConnectionFactory factory)
 {
     Console.WriteLine(" Press [enter] to begin.");
     Console.ReadLine();
     using (var connection = factory.CreateConnection())
         using (var channel = connection.CreateModel())
         {
             SimpleRpcClient client = new SimpleRpcClient(channel, exchange, ExchangeType.Direct, routingKey);
             for (int i = 0; i < 10; i++)
             {
                 var result = client.Call(Encoding.UTF8.GetBytes(i.ToString()));
                 Console.WriteLine($"Result: {Encoding.UTF8.GetString(result)}");
             }
         }
     Console.WriteLine(" Press [Ctrl + C] to exit.");
 }
예제 #9
0
        /// <summary>
        /// 实例化<see cref="MessageQueue"/>
        /// <param name="logging">日志模块</param>
        /// </summary>
        public MessageQueue(ILogging logging)
        {
            Logging    = logging;
            Connection = Instance.Connection;
            Channel    = Connection.CreateModel();

            const string queueName = "rpc_channel";

            Channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: false);
            RpcServer = new RpcServer(new Subscription(Channel, queueName));
            RpcClient = new SimpleRpcClient(Channel, new PublicationAddress(
                                                exchangeType: ExchangeType.Direct,
                                                exchangeName: ExchangeName,
                                                routingKey: queueName));

            //MainLoop方法会阻塞线程, 所以要放到Task中
            Task.Run(() => { RpcServer.MainLoop(); });
        }
예제 #10
0
        public static IEnumerable <ClientRpcInfo> GenerateClientRpcInfoFromConfig(IUserOutput userOutput,
                                                                                  IPasswordRegistry passwordRegistry,
                                                                                  X509Certificate2 certificate,
                                                                                  ILogger logger,
                                                                                  SigningContext signingContext)
        {
            var simulationNodesFile =
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", "simulation.nodes.json");
            var simulationNodes =
                JsonConvert.DeserializeObject <List <SimulationNode> >(File.ReadAllText(simulationNodesFile));

            foreach (var simulationNode in simulationNodes)
            {
                var simpleRpcClient = new SimpleRpcClient(userOutput, passwordRegistry, certificate, logger, signingContext);
                var clientRpcInfo   = new ClientRpcInfo(simulationNode.ToPeerIdentifier(), simpleRpcClient);
                yield return(clientRpcInfo);
            }
        }
예제 #11
0
        public static int Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.Error.WriteLine("Usage: ShutdownableClient <uri> [<secondsdelay>]");
                Console.Error.WriteLine("RabbitMQ .NET client version " + typeof(IModel).Assembly.GetName().Version.ToString());
                Console.Error.WriteLine("Parameters:");
                Console.Error.WriteLine("  <uri> = \"amqp://*****:*****@host:port/vhost\"");
                return(2);
            }

            ConnectionFactory cf = new ConnectionFactory();

            cf.Uri = args[0];
            using (IConnection conn = cf.CreateConnection()) {
                using (IModel ch = conn.CreateModel()) {
                    object[] callArgs = new object[1];
                    if (args.Length > 1)
                    {
                        callArgs[0] = double.Parse(args[1]);
                    }
                    else
                    {
                        callArgs[0] = (double)0.0;
                    }

                    SimpleRpcClient client = new SimpleRpcClient(ch, "ShutdownableServer");
                    client.TimeoutMilliseconds = 5000;
                    client.TimedOut           += new EventHandler(TimedOutHandler);
                    client.Disconnected       += new EventHandler(DisconnectedHandler);
                    object[] reply = client.Call(callArgs);
                    if (reply == null)
                    {
                        Console.WriteLine("Timeout or disconnection.");
                    }
                    else
                    {
                        Console.WriteLine("Reply: {0}", reply[0]);
                    }
                }
            }
            return(0);
        }
예제 #12
0
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory {
                HostName = "localhost"
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    var property = channel.CreateBasicProperties();

                    SimpleRpcClient client = new SimpleRpcClient(channel, new PublicationAddress(ExchangeType.Direct, string.Empty, "rpc_queue"));

                    var bytes = client.Call(Encoding.UTF8.GetBytes("Hello World!!!"));

                    var result = Encoding.UTF8.GetString(bytes);
                    Console.WriteLine(result);
                    Console.Read();
                }
        }
예제 #13
0
 public void Open()
 {
     MessageBox.Show("run subscription open method");
     Initialize();
     try
     {
         using (IConnection conn = cf.CreateConnection())
         {
             using (IModel channel = conn.CreateModel())
             {
                 SimpleRpcClient client = new SimpleRpcClient(channel, exchange, exchangeType, routingKey);
                 byte[]          requestMessageBytes = util.GetBytes("");
                 while (true)
                 {
                     byte[] replyMessageBytes = client.Call(requestMessageBytes);
                     count = count + 1;
                     if (replyMessageBytes != null)
                     {
                         macro.userID = util.GetString(replyMessageBytes);
                         MessageBox.Show("userID" + macro.userID);
                         logger.WriteInfo(string.Format("  Open() queueName {0}", macro.userID));
                         break;
                     }
                     System.Threading.Thread.Sleep(100);
                     if (count > 300)
                     {
                         break;
                     }
                 }
                 channel.Close();
             }
             conn.Close();
         }
     }
     catch (Exception e)
     {
         logger.WriteInfo(e.Message);
     }
 }
예제 #14
0
        private void InvokeWithRpcChoreography(ref ConnectionPoolItem poolItem, ref HttpContext context)
        {
            byte[] payload = context.Request.Body.ReadToEnd();

            IBasicProperties propsIn = poolItem.model.CreateBasicProperties();

            ContextAdapter.FillPropertiesFromRequest(propsIn, context);

            using (var rpcClient = new SimpleRpcClient(
                       model: poolItem.model,
                       queueName: poolItem.queueName
                       ))
            {
                payload = rpcClient.Call(propsIn, payload, out IBasicProperties propsOut);

                ContextAdapter.FillResponseFromProperties(context, propsOut);

                context.Response.Body.Write(payload, 0, payload.Length);

                rpcClient.Subscription.Ack();
            }
        }
예제 #15
0
        static void Main(string[] args)
        {
            string input   = "";
            var    factory = new ConnectionFactory()
            {
                Uri = "amqp://*****:*****@192.168.1.25:5672/test"
            };

            // 心跳超时,默认60秒
            factory.RequestedHeartbeat = 60;
            using (IConnection conn = factory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    while ("exit" != (input = Console.ReadLine()))
                    {
                        var msgBody = new RabbitReq();
                        msgBody.FunctionName = "Login";
                        msgBody.Parameters.Add("Account", "xingchao");
                        msgBody.Parameters.Add("Password", "123456");
                        var msgBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(msgBody));
                        var prop     = new BasicProperties();
                        prop.ContentType     = "application/json";
                        prop.ContentEncoding = "UTF-8";

                        //var client = new SimpleRpcClient(channel, "ExchangeName", ExchangeType.Direct, "RoutingKey");
                        var client = new SimpleRpcClient(channel, "QueueName");
                        IBasicProperties replyProp = new BasicProperties();
                        var replyMsgBytes          = client.Call(prop, msgBytes, out replyProp);

                        var response = JsonConvert.DeserializeObject <RabbitRes>(Encoding.UTF8.GetString(replyMsgBytes));

                        Console.WriteLine(JsonConvert.SerializeObject(response));
                    }
                }
            }
        }