示例#1
0
        void CreateClient()
        {
            switch (_type)
            {
            case MQClientType.Request:
                _clientSocket = _context.CreateRequestSocket();
                break;

            case MQClientType.Subscriber:
                _clientSocket = _context.CreateSubscriberSocket();
                break;

            case MQClientType.Dealer:
                _clientSocket = _context.CreateDealerSocket();
                break;

            case MQClientType.Stream:
                _clientSocket = _context.CreateStreamSocket();
                break;

            case MQClientType.Pull:
                _clientSocket = _context.CreatePullSocket();
                break;

            case MQClientType.XSubscriber:
                _clientSocket = _context.CreateXSubscriberSocket();
                break;

            default:
                _clientSocket = _context.CreateRequestSocket();
                break;
            }
            _clientSocket.Connect("tcp://" + _ip + ":" + _port);
        }
示例#2
0
文件: Program.cs 项目: xuzhe35/netmq
        private static void ClientRoutine(object clientId)
        {
            try
            {
                using (NetMQContext context = NetMQContext.Create())
                {
                    using (RequestSocket req = context.CreateRequestSocket())
                    {
                        req.Connect("tcp://localhost:5555");

                        byte[] message = Encoding.Unicode.GetBytes(string.Format("{0} Hello", clientId));

                        Console.WriteLine("Client {0} sent \"{0} Hello\"", clientId);
                        req.Send(message, message.Length);

                        bool   hasMore;
                        byte[] response = req.Receive(false, out hasMore);
                        Console.WriteLine("Client {0} received \"{1}\"", clientId, Encoding.Unicode.GetString(response));
                    }
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine("Exception on ClientRoutine: {0}", exc.Message);
            }
        }
示例#3
0
 public RequestClient(string address)
 {
     _context = NetMQContext.Create();
     _socket  = _context.CreateRequestSocket();
     _socket.Connect(address);
     Console.WriteLine("RequestClient: connected to {0}", address);
 }
        private NetMQSocket GetOutboundSocket(NetMQContext context)
        {
            NetMQSocket socket;

            switch (Connection.Pattern)
            {
            case MessagePattern.FireAndForget:
                socket = context.CreatePushSocket();
                socket.Connect(Connection.Address);
                break;

            case MessagePattern.RequestResponse:
                socket = context.CreateRequestSocket();
                socket.Connect(Connection.Address);
                break;

            case MessagePattern.PublishSubscribe:
                socket = context.CreatePublisherSocket();
                socket.Bind(Connection.Address);
                break;

            default:
                throw new Exception($"Cannot create an outbound socket for pattern {Connection.Pattern}");
            }

            return(socket);
        }
示例#5
0
        public static void Main(string[] args)
        {
            NetMQContext context = NetMQContext.Create();
            NetMQSocket  server  = context.CreateRequestSocket();

            server.Bind("tcp://*:5555");
            NetMQMessage message = new NetMQMessage();
            NetMQMessage getmass = new NetMQMessage();

            message.Append("Hallo ");
            message.Append(40);

            Client client = new Client();
            Thread t      = new Thread(new ThreadStart(client.runClient));

            t.Start();


            while (true)
            {
                server.SendMessage(message, false);
                getmass = server.ReceiveMessage(false);
                System.Console.WriteLine(getmass.Pop().ConvertToString());
                System.Console.WriteLine(getmass.Pop().ConvertToInt32());
            }
        }
示例#6
0
        static string Client(NetMQContext context, string endpoint, string requestText)
        {
            string answer = "";

            using (NetMQSocket clientSocket = context.CreateRequestSocket())
            {
                clientSocket.Connect(endpoint);

                // while (true)
                // {
                // Console.WriteLine("Please enter your message:");

                clientSocket.Send(requestText);

                answer = clientSocket.ReceiveString();

                //  Console.WriteLine("Answer from server: {0}", answer);

                //  if (message == "exit")
                //  {
                //      break;
                //  }
                // }
            }
            return(answer);
        }
示例#7
0
        static void Main(string[] args)
        {
            string connection = "inproc://HelloWorld";

            using (NetMQContext ctx = NetMQContext.Create())
            {
                using (var server = ctx.CreateResponseSocket())
                {
                    server.Bind(connection);
                    using (var client = ctx.CreateRequestSocket())
                    {
                        client.Connect(connection);

                        client.Send("Hello");

                        string fromClientMessage = server.ReceiveString();
                        Console.WriteLine("From Client: {0}", fromClientMessage);
                        server.Send("Hi Back");

                        string fromServerMessage = client.ReceiveString();
                        Console.WriteLine("From Server: {0}", fromServerMessage);

                        Console.ReadLine();
                    }
                }
            }
        }
        public void SimpleReqRep(string address)
        {
            using (NetMQContext ctx = NetMQContext.Create())
            {
                using (var rep = ctx.CreateResponseSocket())
                {
                    rep.Bind(address);

                    using (var req = ctx.CreateRequestSocket())
                    {
                        req.Connect(address);

                        req.Send("Hi");

                        bool more;

                        string requestString = rep.ReceiveString(out more);

                        Assert.AreEqual("Hi", requestString);
                        Assert.IsFalse(more);

                        rep.Send("Hi2");

                        string responseString = req.ReceiveString(out more);

                        Assert.AreEqual("Hi2", responseString);
                        Assert.IsFalse(more);
                    }
                }
            }
        }
示例#9
0
        public static void Client(NetMQContext context)
        {
            using (NetMQSocket clientSocket = context.CreateRequestSocket())
            {
                clientSocket.Connect("tcp://127.0.0.1:5555");
                JavaScriptSerializer seriallizer = null;
                while (true)
                {
                    seriallizer = new JavaScriptSerializer();
                    Console.WriteLine("Please enter your message:");


                    string       msg      = Console.ReadLine();
                    NetMQMessage message  = new NetMQMessage();
                    var          msgBytes = Common.ByteConvertHelp.Object2Bytes(msg);
                    clientSocket.Send(msgBytes);

                    string answer = clientSocket.ReceiveString();

                    Console.WriteLine("Answer from server: {0}", answer);

                    if (msg == "exit")
                    {
                        break;
                    }
                }
            }
        }
示例#10
0
        private static void Main(string[] args)
        {
            using (NetMQContext ctx = NetMQContext.Create())
            {
                using (var server = ctx.CreateResponseSocket())
                {
                    server.Bind("tcp://127.0.0.1:5556");

                    using (var client = ctx.CreateRequestSocket())
                    {
                        client.Connect("tcp://127.0.0.1:5556");

                        client.Send("Hello");

                        string m1 = server.ReceiveString();

                        Console.WriteLine("From Client: {0}", m1);

                        server.Send("Hi Back");

                        string m2 = client.ReceiveString();

                        Console.WriteLine("From Server: {0}", m2);

                        Console.ReadLine();
                    }
                }
            }
        }
示例#11
0
        /// <summary>
        ///     connects to the broker, if a socket already exists it will be disposed and
        ///     a new socket created and connected
        ///     MDP requires a REQUEST socket for a client
        /// </summary>
        /// <exception cref="ApplicationException">NetMQContext must not be <c>null</c></exception>
        /// <exception cref="ApplicationException">if broker address is empty or <c>null</c></exception>
        private void Connect()
        {
            if (!ReferenceEquals(m_client, null))
            {
                m_client.Dispose();
            }

            if (ReferenceEquals(m_ctx, null))
            {
                throw new ApplicationException("NetMQContext does not exist!");
            }

            m_client = m_ctx.CreateRequestSocket();

            if (m_identity != null)
            {
                m_client.Options.Identity = m_identity;
            }

            // attach the event handler for incoming messages
            m_client.ReceiveReady += ProcessReceiveReady;

            m_client.Connect(m_brokerAddress);

            m_connected = true;

            Log(string.Format("[CLIENT] connecting to broker at {0}", m_brokerAddress));
        }
示例#12
0
        public static string SendRequest(string request, int timeout = 5000)
        {
            string joshuaHost = "10.30.16.16";
            string joshuaPort = "2804";

            //logHandler.WriteLog(string.Format("Sent request: {0}", request));
            using (NetMQContext context = NetMQContext.Create())
            {
                using (NetMQSocket clientSocket = context.CreateRequestSocket())
                {
                    try
                    {
                        clientSocket.Connect(string.Format("tcp://{0}:{1}", joshuaHost, joshuaPort));
                        clientSocket.Options.ReceiveTimeout = TimeSpan.FromMilliseconds(timeout);

                        clientSocket.Send(request);
                        //logHandler.WriteLog(string.Format("Returning {0} bytes", bytes.Length));
                        return(clientSocket.ReceiveString());
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(string.Format("Exception getting data: {0}", e));
                        return(null);
                    }
                }
            }
        }
        public string GetQuoteInfoRaw(params string[] tickerListToQuote)
        {
            if (tickerListToQuote == null || !tickerListToQuote.Any())
            {
                return(string.Empty);
            }

            using (var client = context.CreateRequestSocket())
            {
                client.Connect(MarketDataSettings.SnapshotDataServerAddress);
                var joinedList = string.Join(",", tickerListToQuote);

                client.SendFrame(joinedList);
                var response = client.ReceiveFrameString();
                return(response);
            }
        }
示例#14
0
        internal NmqMessageSender(Uri serviceUri)
        {
            context = NetMQContext.Create();
            socket  = context.CreateRequestSocket();
            var address = string.Format("tcp://{0}:{1}", serviceUri.Host, serviceUri.Port);

            socket.Connect(address);
        }
示例#15
0
        public void Monitoring()
        {
            ManualResetEvent listeningEvent = new ManualResetEvent(false);
            ManualResetEvent acceptedEvent  = new ManualResetEvent(false);
            ManualResetEvent connectedEvent = new ManualResetEvent(false);


            using (NetMQContext contex = NetMQContext.Create())
            {
                Poller poller = new Poller();

                using (var rep = contex.CreateResponseSocket())
                {
                    using (NetMQMonitor monitor = new NetMQMonitor(contex, rep, "inproc://rep.inproc", SocketEvent.Accepted | SocketEvent.Listening))
                    {
                        monitor.Accepted  += (s, a) => acceptedEvent.Set();
                        monitor.Listening += (s, a) => listeningEvent.Set();

                        monitor.AttachToPoller(poller);

                        rep.Bind("tcp://127.0.0.1:5002");

                        using (var req = contex.CreateRequestSocket())
                        {
                            using (NetMQMonitor reqMonitor = new NetMQMonitor(contex, req, "inproc://req.inproc", SocketEvent.Connected))
                            {
                                reqMonitor.Connected += (s, a) => connectedEvent.Set();

                                reqMonitor.AttachToPoller(poller);
                                try
                                {
                                    var pollerTask = Task.Factory.StartNew(poller.Start);

                                    req.Connect("tcp://127.0.0.1:5002");
                                    req.Send("a");

                                    bool more;

                                    string m = rep.ReceiveString(out more);

                                    rep.Send("b");

                                    string m2 = req.ReceiveString(out more);

                                    Assert.IsTrue(listeningEvent.WaitOne(300));
                                    Assert.IsTrue(connectedEvent.WaitOne(300));
                                    Assert.IsTrue(acceptedEvent.WaitOne(300));
                                }
                                finally
                                {
                                    poller.Stop();
                                }
                            }
                        }
                    }
                }
            }
        }
示例#16
0
        public void Monitoring()
        {
            bool listening = false;
            bool accepted  = false;

            using (NetMQContext contex = NetMQContext.Create())
            {
                using (var rep = contex.CreateResponseSocket())
                {
                    using (NetMQMonitor monitor = new NetMQMonitor(contex, rep, "inproc://rep.inproc", SocketEvent.Accepted | SocketEvent.Listening))
                    {
                        monitor.Accepted += (s, a) =>
                        {
                            accepted = true;
                            //Console.WriteLine(a.Socket.LocalEndPoint.ToString());
                        };
                        monitor.Listening += (s, a) =>
                        {
                            listening = true;
                            Console.WriteLine(a.Socket.LocalEndPoint.ToString());
                        };

                        monitor.Timeout = TimeSpan.FromMilliseconds(100);

                        var pollerTask = Task.Factory.StartNew(monitor.Start);

                        rep.Bind("tcp://127.0.0.1:5002");

                        using (var req = contex.CreateRequestSocket())
                        {
                            req.Connect("tcp://127.0.0.1:5002");
                            req.Send("a");

                            bool more;

                            string m = rep.ReceiveString(out more);

                            rep.Send("b");

                            string m2 = req.ReceiveString(out more);

                            Thread.Sleep(200);

                            Assert.IsTrue(listening);
                            Assert.IsTrue(accepted);

                            monitor.Stop();

                            Thread.Sleep(200);

                            Assert.IsTrue(pollerTask.IsCompleted);
                        }
                    }
                }
            }
        }
示例#17
0
 public RequestClientEx(NetMQContext context, string address)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     _socket = context.CreateRequestSocket();
     _socket.Connect(address);
     Console.WriteLine("RequestClientEx: connected to {0} ({1:x})", address, this.GetHashCode());
 }
示例#18
0
文件: Program.cs 项目: fhchina/netmq
        /// <summary>
        ///     just to create the REQ socket
        /// </summary>
        /// <param name="context">current NetMQContext</param>
        /// <param name="id">the name for the client</param>
        /// <returns>the connected REQ socket</returns>
        private static RequestSocket CreateSocket(NetMQContext context, string id)
        {
            var client = context.CreateRequestSocket();

            client.Options.Identity = Encoding.UTF8.GetBytes(id);
            client.Options.Linger   = TimeSpan.Zero;
            // set the event to be called upon arrival of a message
            client.ReceiveReady += OnClientReceiveReady;
            client.Connect(Commons.QUEUE_FRONTEND);

            return(client);
        }
示例#19
0
        private static RequestSocket CreateServerSocket(NetMQContext context)
        {
            Console.WriteLine("C: Connecting to server...");

            var client = context.CreateRequestSocket();

            client.Connect(SERVER_ENDPOINT);
            client.Options.Linger = TimeSpan.Zero;
            client.ReceiveReady  += ClientOnReceiveReady;

            return(client);
        }
示例#20
0
 static void Main()
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     using (NetMQContext context = NetMQContext.Create())
     {
         using (NetMQSocket socket = context.CreateRequestSocket())
         {
             Application.Run(new ConnectionForm(context, socket));
         }
     }
 }
示例#21
0
 public byte[] GetSnapshot(string topic)
 {
     using (NetMQContext ctx = NetMQContext.Create())
     {
         using (RequestSocket socket = ctx.CreateRequestSocket())
         {
             socket.Connect(Address);
             socket.Send(topic);
             NetMQMessage message = socket.ReceiveMessage();
             return(message.Last.ToByteArray());
         }
     }
 }
示例#22
0
        public void ErrorCodeTest()
        {
            bool eventArrived = false;

            using (NetMQContext contex = NetMQContext.Create())
            {
                using (var req = contex.CreateRequestSocket())
                {
                    using (var rep = contex.CreateResponseSocket())
                    {
                        using (NetMQMonitor monitor =
                                   new NetMQMonitor(contex, req, "inproc://rep.inproc", SocketEvent.ConnectDelayed))
                        {
                            monitor.ConnectDelayed += (s, a) =>
                            {
                                eventArrived = true;
                            };

                            monitor.Timeout = TimeSpan.FromMilliseconds(100);

                            var pollerTask = Task.Factory.StartNew(monitor.Start);

                            rep.Bind("tcp://127.0.0.1:5002");


                            req.Connect("tcp://127.0.0.1:5002");
                            req.Send("a");

                            bool more;

                            string m = rep.ReceiveString(out more);

                            rep.Send("b");

                            string m2 = req.ReceiveString(out more);

                            Thread.Sleep(200);

                            Assert.IsTrue(eventArrived);

                            monitor.Stop();

                            Thread.Sleep(200);

                            Assert.IsTrue(pollerTask.IsCompleted);
                        }
                    }
                }
            }
        }
示例#23
0
        public SharpDBConnection GetConnection()
        {
            NetMQSocket socket = m_context.CreateRequestSocket();

            socket.Options.CopyMessages = false;
            socket.Options.Linger       = TimeSpan.FromSeconds(5);
            socket.Connect(ConnectionString);

            var connection = new SharpDBConnection(this, socket, SerializerFactory());

            m_connections.Add(connection);

            return(connection);
        }
示例#24
0
文件: Program.cs 项目: xzoth/netmq
        private static RequestSocket CreateServerSocket(NetMQContext context)
        {
            Console.WriteLine("C: Connecting to server...");

            var client = context.CreateRequestSocket();

            client.Options.Linger = TimeSpan.Zero;
            Guid guid = Guid.NewGuid();

            client.Options.Identity = Encoding.Unicode.GetBytes(guid.ToString());
            client.Connect(ServerEndpoint);
            client.ReceiveReady += ClientOnReceiveReady;

            return(client);
        }
示例#25
0
        public static void Blow(string song, string notes)
        {
            new Thread(() => {
                using (NetMQSocket request_socket = context.CreateRequestSocket()) {
                    request_socket.Connect(string.Format("tcp://{0}:{1}", Address, RequestPort));
                    request_socket.SendMore("blow").SendMore(song).Send(notes);

                    string response = request_socket.ReceiveString();
                    Console.WriteLine("[request_socket] Response: {0}", response);

                    request_socket.Close();
                    request_socket.Dispose();
                }
            }).Start();
        }
示例#26
0
        public string Request(string service, string msg, int timeoutmsec)
        {
            string      resp    = string.Empty;
            LinkAddress address = config.ReqRep.FindLinkAddress(service);

            if (address == null)
            {
                return(resp);
            }

            bool   pollResult = false;
            string requestId  = Guid.NewGuid().ToString();

            using (NetMQContext context = NetMQContext.Create())
            {
                NetMQSocket client = context.CreateRequestSocket();
                client.Options.Linger   = TimeSpan.Zero;
                client.Options.Identity = Encoding.UTF8.GetBytes(requestId);
                client.Connect(address.Address);
                try
                {
                    byte[] data = Encoding.UTF8.GetBytes(msg);
                    client.Send(data);
                }
                catch (Exception)
                {
                    client.Disconnect(address.Address);
                    client.Dispose();
                    return(resp);
                }

                client.ReceiveReady += ClientOnReceiveReady;
                pollResult           = client.Poll(TimeSpan.FromMilliseconds(timeoutmsec));
                client.ReceiveReady -= ClientOnReceiveReady;
                client.Disconnect(address.Address);
                client.Dispose();
            }

            if (pollResult)
            {
                if (responseMsgs.ContainsKey(requestId))
                {
                    responseMsgs.TryRemove(requestId, out resp);
                }
            }

            return(resp);
        }
示例#27
0
 private void start(CancellationToken token, string address, TaskCompletionSource <bool> ready)
 {
     using (var socket = _context.CreateRequestSocket())
     {
         socket.Connect(address);
         ready.SetResult(true);
         while (token.IsCancellationRequested == false)
         {
             var bytes = Encoding.ASCII.GetBytes(_id);
             socket.Send(bytes);
             var response = socket.Receive();
             var message  = Encoding.ASCII.GetString(response);
             Console.WriteLine("[{0}] Received - {1}", _id, message);
         }
     }
 }
示例#28
0
        private void CreateClient(NetMQContext ctx, string prefix)
        {
            Task.Run(() =>
            {
                var client = ctx.CreateRequestSocket();
                clients.Add(client);
                client.Connect("tcp://127.0.0.1:5556");
                client.Send(string.Format("{0}Hello", prefix));

                //read client message
                var echoedServerMessage = client.ReceiveString();
                Console.WriteLine(
                    "\r\nClient Prefix is : '{0}', Server Message : '{1}'",
                    prefix, echoedServerMessage);
            });
        }
示例#29
0
        public void TestKeepAlive()
        {
            // there is no way to test tcp keep alive without disconnect the cable, we just testing that is not crashing the system
            using (NetMQContext context = NetMQContext.Create())
            {
                using (var responseSocket = context.CreateResponseSocket())
                {
                    responseSocket.Options.TcpKeepalive         = true;
                    responseSocket.Options.TcpKeepaliveIdle     = TimeSpan.FromSeconds(5);
                    responseSocket.Options.TcpKeepaliveInterval = TimeSpan.FromSeconds(1);

                    responseSocket.Bind("tcp://127.0.0.1:5555");

                    using (var requestSocket = context.CreateRequestSocket())
                    {
                        requestSocket.Options.TcpKeepalive         = true;
                        requestSocket.Options.TcpKeepaliveIdle     = TimeSpan.FromSeconds(5);
                        requestSocket.Options.TcpKeepaliveInterval = TimeSpan.FromSeconds(1);

                        requestSocket.Connect("tcp://127.0.0.1:5555");

                        requestSocket.Send("1");

                        bool   more;
                        string m = responseSocket.ReceiveString(out more);

                        Assert.IsFalse(more);
                        Assert.AreEqual("1", m);

                        responseSocket.Send("2");

                        string m2 = requestSocket.ReceiveString(out more);

                        Assert.IsFalse(more);
                        Assert.AreEqual("2", m2);

                        Assert.IsTrue(requestSocket.Options.TcpKeepalive);
                        Assert.AreEqual(TimeSpan.FromSeconds(5), requestSocket.Options.TcpKeepaliveIdle);
                        Assert.AreEqual(TimeSpan.FromSeconds(1), requestSocket.Options.TcpKeepaliveInterval);

                        Assert.IsTrue(responseSocket.Options.TcpKeepalive);
                        Assert.AreEqual(TimeSpan.FromSeconds(5), responseSocket.Options.TcpKeepaliveIdle);
                        Assert.AreEqual(TimeSpan.FromSeconds(1), responseSocket.Options.TcpKeepaliveInterval);
                    }
                }
            }
        }
示例#30
0
        public void SendMessageInResponeBeforeReceiving()
        {
            using (NetMQContext ctx = NetMQContext.Create())
            {
                using (var rep = ctx.CreateResponseSocket())
                {
                    rep.Bind("tcp://localhost:5001");

                    using (var req = ctx.CreateRequestSocket())
                    {
                        req.Connect("tcp://localhost:5001");

                        var ex = Assert.Throws <FiniteStateMachineException>(() => rep.Send("1"));
                    }
                }
            }
        }
示例#31
0
 protected override NetMQSocket CreateClientSocket(NetMQContext context)
 {
     return context.CreateRequestSocket();
 }