当前位置: 首页>>代码示例>>C#>>正文


C# ZSocket.ReceiveMessage方法代码示例

本文整理汇总了C#中ZSocket.ReceiveMessage方法的典型用法代码示例。如果您正苦于以下问题:C# ZSocket.ReceiveMessage方法的具体用法?C# ZSocket.ReceiveMessage怎么用?C# ZSocket.ReceiveMessage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ZSocket的用法示例。


在下文中一共展示了ZSocket.ReceiveMessage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: LBBroker_Client

		// Basic request-reply client using REQ socket
		static void LBBroker_Client(ZContext context, int i)
		{
			// Create a socket
			using (var client = new ZSocket(context, ZSocketType.REQ))
			{
				// Set a printable identity
				client.IdentityString = "CLIENT" + i;

				// Connect
				client.Connect("inproc://frontend");

				using (var request = new ZMessage())
				{
					request.Add(new ZFrame("Hello"));

					// Send request
					client.Send(request);
				}

				// Receive reply
				using (ZMessage reply = client.ReceiveMessage())
				{
					Console.WriteLine("CLIENT{0}: {1}", i, reply[0].ReadString());
				}
			}
		}
开发者ID:ray-zong,项目名称:zguide,代码行数:27,代码来源:lbbroker.cs

示例2: Main

        static void Main(string[] args)
        {
            var queueAddress = Config.Get("Queues.Fulfilment.Address");

            using (var context = new ZContext())
            using (var receiver = new ZSocket(context, ZSocketType.PULL))
            {
                receiver.Bind(queueAddress);
                Console.WriteLine("Listening for messages on: " + queueAddress);

                while (true)
                {
                    using (var message = receiver.ReceiveMessage())
                    {
                        var headerFrame = message.First();
                        var header = JsonConvert.DeserializeObject<Header>(headerFrame.ReadString());
                        Console.WriteLine("* Received message, ID: {0}, body type: {1}, handled count: {2}", header.MessageId, header.BodyType, header.HandledCount);

                        //assume this is a permanent failure
                        if (header.HandledCount < 3)
                        {
                            Console.WriteLine("** Handling message. Previous attempts: {0}", header.HandledCount);
                            Handle(header, message.ElementAt(1));
                        }
                        else
                        {
                            Console.WriteLine("!! Message has failed {0} times. Not processing. Last exception: {1}", header.HandledCount, header.LastExceptionMessage);
                            //TODO - forward to error queue
                        }
                    }
                    Thread.Sleep(100);
                }
            }
        }
开发者ID:sixeyed,项目名称:handling-failures,代码行数:34,代码来源:Program.cs

示例3: PSEnvSub

		public static void PSEnvSub(string[] args)
		{
			//
			// Pubsub envelope subscriber
			//
			// Author: metadings
			//

			// Prepare our context and subscriber
			using (var context = new ZContext())
			using (var subscriber = new ZSocket(context, ZSocketType.SUB))
			{
				subscriber.Connect("tcp://127.0.0.1:5563");
				subscriber.Subscribe("B");

				int subscribed = 0;
				while (true)
				{
					using (ZMessage message = subscriber.ReceiveMessage())
					{
						subscribed++;

						// Read envelope with address
						string address = message[0].ReadString();

						// Read message contents
						string contents = message[1].ReadString();

						Console.WriteLine("{0}. [{1}] {2}", subscribed, address, contents);
					}
				}
			}
		}
开发者ID:ChenXuJasper,项目名称:zguide,代码行数:33,代码来源:psenvsub.cs

示例4: LBBroker_Worker

		static void LBBroker_Worker(ZContext context, int i)
		{
			// This is the worker task, using a REQ socket to do load-balancing.

			// Create socket
			using (var worker = new ZSocket(context, ZSocketType.REQ))
			{
				// Set a printable identity
				worker.IdentityString = "WORKER" + i;

				// Connect
				worker.Connect("inproc://backend");

				// Tell broker we're ready for work
				using (var ready = new ZFrame("READY"))
				{
					worker.Send(ready);
				}

				ZError error;
				ZMessage request;

				while (true)
				{
					// Get request
					if (null == (request = worker.ReceiveMessage(out error)))
					{
						// We are using "out error",
						// to NOT throw a ZException ETERM
						if (error == ZError.ETERM)
							break;

						throw new ZException(error);
					}

					using (request)
					{
						string worker_id = request[0].ReadString();

						string requestText = request[2].ReadString();
						Console.WriteLine("WORKER{0}: {1}", i, requestText);

						// Send reply
						using (var commit = new ZMessage())
						{
							commit.Add(new ZFrame(worker_id));
							commit.Add(new ZFrame());
							commit.Add(new ZFrame("OK"));

							worker.Send(commit);
						}
					}
				}
			}
		}
开发者ID:ray-zong,项目名称:zguide,代码行数:55,代码来源:lbbroker.cs

示例5: RTReq

		public static void RTReq(string[] args)
		{
			//
			// ROUTER-to-REQ example
			//
			// While this example runs in a single process, that is only to make
			// it easier to start and stop the example. Each thread has its own
			// context and conceptually acts as a separate process.
			//
			// Author: metadings
			//

			using (var context = new ZContext())
			using (var broker = new ZSocket(context, ZSocketType.ROUTER))
			{
				broker.Bind("tcp://*:5671");

				for (int i = 0; i < RTReq_Workers; ++i)
				{
					int j = i; new Thread(() => RTReq_Worker(j)).Start();
				}

				var stopwatch = new Stopwatch();
				stopwatch.Start();

				// Run for five seconds and then tell workers to end
				int workers_fired = 0;
				while (true)
				{
					// Next message gives us least recently used worker
					using (ZMessage identity = broker.ReceiveMessage())
					{
						broker.SendMore(identity[0]);
						broker.SendMore(new ZFrame());

						// Encourage workers until it's time to fire them
						if (stopwatch.Elapsed < TimeSpan.FromSeconds(5))
						{
							broker.Send(new ZFrame("Work harder!"));
						}
						else
						{
							broker.Send(new ZFrame("Fired!"));

							if (++workers_fired == RTReq_Workers)
							{
								break;
							}
						}
					}
				}
			}
		}
开发者ID:ChenXuJasper,项目名称:zguide,代码行数:53,代码来源:rtreq.cs

示例6: PathoSub

		public static void PathoSub(string[] args)
		{
			//
			// Pathological subscriber
			// Subscribes to one random topic and prints received messages
			//
			// Author: metadings
			//

			if (args == null || args.Length < 1)
			{
				Console.WriteLine();
				Console.WriteLine("Usage: ./{0} PathoSub [Endpoint]", AppDomain.CurrentDomain.FriendlyName);
				Console.WriteLine();
				Console.WriteLine("    Endpoint  Where PathoSub should connect to.");
				Console.WriteLine("              Default is tcp://127.0.0.1:5556");
				Console.WriteLine();
				args = new string[] { "tcp://127.0.0.1:5556" };
			}

			using (var context = new ZContext())
			using (var subscriber = new ZSocket(context, ZSocketType.SUB))
			{
				subscriber.Connect(args[0]);

				var rnd = new Random();
				var subscription = string.Format("{0:D3}", rnd.Next(1000));
				subscriber.Subscribe(subscription);

				ZMessage msg;
				ZError error;
				while (true)
				{
					if (null == (msg = subscriber.ReceiveMessage(out error)))
					{
						if (error == ZError.ETERM)
							break;	// Interrupted
						throw new ZException(error);
					}
					using (msg)
					{
						if (msg[0].ReadString() != subscription)
						{
							throw new InvalidOperationException();
						}
						Console.WriteLine(msg[1].ReadString());
					}
				}
			}
		}
开发者ID:ChenXuJasper,项目名称:zguide,代码行数:50,代码来源:pathosub.cs

示例7: Identity

		public static void Identity(string[] args)
		{
			//
			// Demonstrate request-reply identities
			//
			// Author: metadings
			//

			using (var context = new ZContext())
			using (var sink = new ZSocket(context, ZSocketType.ROUTER))
			{
				sink.Bind("inproc://example");

				// First allow 0MQ to set the identity
				using (var anonymous = new ZSocket(context, ZSocketType.REQ))
				{
					anonymous.Connect("inproc://example");
					anonymous.Send(new ZFrame("ROUTER uses REQ's generated 5 byte identity"));
				}
				using (ZMessage msg = sink.ReceiveMessage())
				{    
					msg.DumpZmsg("--------------------------");
				}

				// Then set the identity ourselves
				using (var identified = new ZSocket(context, ZSocketType.REQ))
				{
					identified.IdentityString = "PEER2";
					identified.Connect("inproc://example");
					identified.Send(new ZFrame("ROUTER uses REQ's socket identity"));
				}
				using (ZMessage msg = sink.ReceiveMessage())
				{
					msg.DumpZmsg("--------------------------");
				}
			}
		}
开发者ID:ChenXuJasper,项目名称:zguide,代码行数:37,代码来源:identity.cs

示例8: FLServer1

		public static void FLServer1(string[] args)
		{
			//
			// Freelance server - Model 1
			// Trivial echo service
			//
			// Author: metadings
			//

			if (args == null || args.Length < 1)
			{
				Console.WriteLine();
				Console.WriteLine("Usage: ./{0} FLServer1 [Endpoint]", AppDomain.CurrentDomain.FriendlyName);
				Console.WriteLine();
				Console.WriteLine("    Endpoint  Where FLServer1 should bind on.");
				Console.WriteLine("              Default is tcp://127.0.0.1:7780");
				Console.WriteLine();
				args = new string[] { "tcp://127.0.0.1:7780" };
			}

			using (var context = new ZContext())
			using (var server = new ZSocket(context, ZSocketType.REP)) 
			{
				server.Bind(args[0]);

				Console.WriteLine("I: echo service is ready at {0}", args[0]);

				ZMessage message;
				ZError error;
				while (true)
				{
					if (null != (message = server.ReceiveMessage(out error)))
					{
						using (message)
						{
							server.Send(message);
						}
					}
					else
					{
						if (error == ZError.ETERM)
							return;	// Interrupted
						throw new ZException(error);
					}
				}
			}
		}
开发者ID:ray-zong,项目名称:zguide,代码行数:47,代码来源:flserver1.cs

示例9: LPServer

		//
		// Lazy Pirate server
		// Binds REP socket to tcp://*:5555
		// Like hwserver except:
		// - echoes request as-is
		// - randomly runs slowly, or exits to simulate a crash.
		//
		// Author: metadings
		//

		public static void LPServer(string[] args)
		{
			using (var context = new ZContext())
			using (var responder = new ZSocket(context, ZSocketType.REP))
			{
				responder.Bind("tcp://*:5555");

				ZError error;
				int cycles = 0;
				var rnd = new Random();

				while (true)
				{
					ZMessage incoming;
					if (null == (incoming = responder.ReceiveMessage(out error)))
					{
						if (error == ZError.ETERM)
							return;	// Interrupted
						throw new ZException(error);
					}
					using (incoming)
					{
						++cycles;

						// Simulate various problems, after a few cycles
						if (cycles > 16 && rnd.Next(16) == 0)
						{
							Console.WriteLine("I: simulating a crash");
							break;
						}
						else if (cycles > 4 && rnd.Next(4) == 0)
						{
							Console.WriteLine("I: simulating CPU overload");
							Thread.Sleep(1000);
						}

						Console.WriteLine("I: normal request ({0})", incoming[0].ReadInt32());

						Thread.Sleep(1); // Do some heavy work

						responder.Send(incoming);
					}
				}
			}
		}
开发者ID:ray-zong,项目名称:zguide,代码行数:55,代码来源:lpserver.cs

示例10: Main

        public static void Main(string[] args)
        {
            //
            // Pubsub envelope subscriber
            //
            // Author: metadings
            //

            string topic;

            if (args == null || !args.Any())
            {
                topic = string.Empty;
                Console.WriteLine("Not filtering messages.");
            }
            else
            {
                topic = args[0];
                Console.WriteLine("Filtering messages by topic '{0}'.", topic);
            }

            // Prepare our context and subscriber
            using (var context = new ZContext())
            using (var subscriber = new ZSocket(context, ZSocketType.SUB))
            {
                subscriber.Connect("tcp://127.0.0.1:5563");
                subscriber.Subscribe(topic);

                while (true)
                {
                    using (ZMessage message = subscriber.ReceiveMessage())
                    {
                        // Read envelope with address
                        string address = message[0].ReadString();

                        // Read message contents
                        string contents = message[1].ReadString();

                        Console.WriteLine("[{0}] {1}", address, contents);
                    }
                }
            }
        }
开发者ID:dshaneg,项目名称:zmqpoc,代码行数:43,代码来源:Program.cs

示例11: BackendHandler

        /// <summary>
        /// Forwards replies from the backend socket to the frontend socket.
        /// </summary>
        protected override bool BackendHandler(ZSocket sock, out ZMessage message, out ZError error)
        {
            error = default(ZError);
            message = null;

            // receiving scope
            // DEALER: normal movemsg
            ZMessage incoming = null;
            if (!sock.ReceiveMessage(ref incoming, /* ZSocketFlags.DontWait */ ZSocketFlags.None, out error))
            {
                return false;
            }

            using (incoming)
            {
                // STREAM: write frames: identity, body, identity, empty
                // Read identity
                int ic = (int)incoming[0].Length;
                var identityBytes = new byte[ic];
                incoming[0].Read(identityBytes, 0, ic);

                // Remove DEALER's delimiter
                incoming.RemoveAt(1);

                // Append Identity frame
                var identity0 = new ZFrame(identityBytes);
                incoming.Add(identity0);

                // Append STREAM's empty delimiter frame
                incoming.Add(new ZFrame());

                if (!SendMsg(FrontendSocket, incoming, out error))
                {
                    return false;
                }
            }

            return true;
        }
开发者ID:Giten2004,项目名称:clrzmq4,代码行数:42,代码来源:StreamDealerDevice.cs

示例12: AsyncSrv_ServerWorker

		static void AsyncSrv_ServerWorker(ZContext context, int i) 
		{
			// Each worker task works on one request at a time and sends a random number
			// of replies back, with random delays between replies:

			using (var worker = new ZSocket(context, ZSocketType.DEALER))
			{
				worker.Connect("inproc://backend");

				ZError error;
				ZMessage request;
				var rnd = new Random();

				while (true)
				{
					if (null == (request = worker.ReceiveMessage(out error)))
					{
						if (error == ZError.ETERM)
							return;	// Interrupted
						throw new ZException(error);
					}
					using (request)
					{
						// The DEALER socket gives us the reply envelope and message
						string identity = request[1].ReadString();
						string content = request[2].ReadString();

						// Send 0..4 replies back
						int replies = rnd.Next(5);
						for (int reply = 0; reply < replies; ++reply)
						{
							// Sleep for some fraction of a second
							Thread.Sleep(rnd.Next(1000) + 1);

							using (var response = new ZMessage())
							{
								response.Add(new ZFrame(identity));
								response.Add(new ZFrame(content));

								if (!worker.Send(response, out error))
								{
									if (error == ZError.ETERM)
										return;	// Interrupted
									throw new ZException(error);
								}
							}
						}
					}
				}
			}
		}
开发者ID:ChenXuJasper,项目名称:zguide,代码行数:51,代码来源:asyncsrv.cs

示例13: Tripping_WorkerTask

        //  .split worker task
        //  Here is the worker task. All it does is receive a message, and
        //  bounce it back the way it came:
        static void Tripping_WorkerTask(ZContext ctx)
        {
            using (var worker = new ZSocket(ctx, ZSocketType.DEALER))
            {
                worker.Connect("tcp://127.0.0.1:5556");

                while (true)
                {
                    ZError error;
                    ZMessage msg = worker.ReceiveMessage(out error);
                    if (error == null && worker.Send(msg, out error))
                        continue;
                    // errorhandling, context terminated or sth else
                    if (error.Equals(ZError.ETERM))
                        return; // Interrupted
                    throw new ZException(error);
                }
            }
        }
开发者ID:potatogim,项目名称:zguide,代码行数:22,代码来源:tripping.cs

示例14: FLServer3

		public static void FLServer3(string[] args)
		{
			//
			// Freelance server - Model 3
			// Uses an ROUTER/ROUTER socket but just one thread
			//
			// Author: metadings
			//

			// Prepare server socket with predictable identity
			string bind_endpoint = "tcp://*:5555";
			string connect_endpoint = "tcp://127.0.0.1:5555";

			using (var context = new ZContext())
			using (var server = new ZSocket(context, ZSocketType.ROUTER))
			{
				Console.CancelKeyPress += (s, ea) =>
				{
					ea.Cancel = true;
					context.Shutdown();
				};

				server.IdentityString = connect_endpoint;
				server.Bind(bind_endpoint);
				Console.WriteLine("I: service is ready as {0}", bind_endpoint);

				ZError error;
				ZMessage request;
				while (true)
				{
					if (null == (request = server.ReceiveMessage(out error)))
					{
						if (error == ZError.ETERM)
							break;	// Interrupted
						throw new ZException(error);
					}
					using (var response = new ZMessage())
					{
						ZFrame identity;

						using (request)
						{
							if (Verbose) Console_WriteZMessage("Receiving", request);

							// Frame 0: identity of client
							// Frame 1: PING, or client control frame
							// Frame 2: request body

							identity = request.Pop();

							ZFrame control = request.Pop();
							string controlMessage = control.ReadString();

							if (controlMessage == "PING")
							{
								control.Dispose();
								response.Add(new ZFrame("PONG"));
							}
							else
							{
								response.Add(control);
								response.Add(new ZFrame("OK"));
							}
						}

						response.Prepend(identity);

						if (Verbose) Console_WriteZMessage("Sending  ", response);
						if (!server.Send(response, out error))
						{
							if (error == ZError.ETERM)
								break;	// Interrupted
							throw new ZException(error);
						}
					}
				}
				if (error == ZError.ETERM)
				{
					Console.WriteLine("W: interrupted");
				}
			}
		}
开发者ID:ChenXuJasper,项目名称:zguide,代码行数:82,代码来源:flserver3.cs

示例15: SPWorker

        public static void SPWorker(string[] args)
        {
            //
            // Simple Pirate worker
            // Connects REQ socket to tcp://127.0.0.1:5556
            // Implements worker part of load-balancing
            //
            // Author: metadings
            //

            var rnd = new Random();
            if (args == null || args.Length < 1)
            {
                args = new string[] { "World" + rnd.Next() };
            }
            string name = args[0];

            using (var context = new ZContext())
            using (var worker = new ZSocket(context, ZSocketType.REQ))
            {
                worker.Identity = Encoding.UTF8.GetBytes(name);
                worker.Connect("tcp://127.0.0.1:5556");

                Console.WriteLine("I: ({0}) worker ready", name);

                using (var outgoing = new ZFrame("READY"))
                {
                    worker.Send(outgoing);
                }

                int cycles = 0;
                ZError error;
                ZMessage incoming;

                while (true)
                {
                    if (null == (incoming = worker.ReceiveMessage(out error)))
                    {
                        if (error == ZError.ETERM)
                            return;

                        throw new ZException(error);
                    }
                    using (incoming)
                    {
                        // Simulate various problems, after a few cycles
                        cycles++;

                        if (cycles > 3 && rnd.Next(5) == 0)
                        {
                            Console.WriteLine("I: ({0}) simulating a crash", name);
                            return;
                        }
                        else if (cycles > 3 && rnd.Next(5) == 0)
                        {
                            Console.WriteLine("I: ({0}) simulating CPU overload", name);
                            Thread.Sleep(500);
                        }

                        Console.WriteLine("I: ({0}) normal reply", name);

                        Thread.Sleep(1); // Do some heavy work

                        // Send message back
                        worker.Send(incoming);
                    }
                }

            }
        }
开发者ID:ChenXuJasper,项目名称:zguide,代码行数:70,代码来源:spworker.cs


注:本文中的ZSocket.ReceiveMessage方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。