public void SimplePubSub() { using (NetMQContext contex = NetMQContext.Create()) { using (var pub = contex.CreatePublisherSocket()) { pub.Bind("tcp://127.0.0.1:5002"); using (var sub = contex.CreateSubscriberSocket()) { sub.Connect("tcp://127.0.0.1:5002"); sub.Subscribe(""); // let the subscrbier connect to the publisher before sending a message Thread.Sleep(500); pub.Send("Hello"); bool more; string m = sub.ReceiveString(out more); Assert.AreEqual("Hello", m); Assert.False(more); } } } }
/// <summary> /// <para>Constructs a publisher socket.</para> /// </summary> /// <param name="address">Address to which to connect (for example: tcp://localhost:9001).</param> /// <param name="context">ZMQ Context.</param> /// <param name="verboseLog">Enable tracing of each event published.</param> /// <param name="traceWriter">Traces</param> internal Publisher(string address, NetMQContext context, bool verboseLog, ITraceWriter traceWriter) { if (context == null) { throw new ArgumentNullException("context"); } if (string.IsNullOrEmpty(address)) { throw new ArgumentNullException("address"); } if (traceWriter == null) { throw new ArgumentNullException("traceWriter"); } _traces = traceWriter; _verboseLog = verboseLog; _instanceHashCode = this.GetHashCode(); _socket = context.CreatePublisherSocket(); _socket.Options.SendHighWatermark = 100000; try { _socket.Connect(address); _traces.Debug("Publisher({0:x}) created ({1}).", _instanceHashCode, address); } catch (Exception ex) { _traces.Error(ex); _socket.Dispose(); throw; } }
/// <summary> /// Initializes a new instance of the <see cref="ForwarderDevice"/> class. /// </summary> /// <param name="context">The <see cref="NetMQContext"/> to use when creating the sockets.</param> /// <param name="poller">The <see cref="Poller"/> to use.</param> /// <param name="frontendBindAddress">The endpoint used to bind the frontend socket.</param> /// <param name="backendBindAddress">The endpoint used to bind the backend socket.</param> /// <param name="mode">The <see cref="DeviceMode"/> for the device.</param> public ForwarderDevice(NetMQContext context, Poller poller, string frontendBindAddress, string backendBindAddress, DeviceMode mode = DeviceMode.Threaded) : base(poller, context.CreateSubscriberSocket(), context.CreatePublisherSocket(), mode) { FrontendSetup.Bind(frontendBindAddress); BackendSetup.Bind(backendBindAddress); }
public void RunPipeline(PairSocket shim) { publisherSocket = context.CreatePublisherSocket(); publisherSocket.Bind("tcp://*:" + StreamingProtocol.Port); snapshotSocket = context.CreateResponseSocket(); snapshotSocket.Bind("tcp://*:" + SnapshotProtocol.Port); snapshotSocket.ReceiveReady += OnSnapshotReady; shim.ReceiveReady += OnShimReady; heartbeatTimer = new NetMQTimer(StreamingProtocol.HeartbeatInterval); heartbeatTimer.Elapsed += OnHeartbeatTimerElapsed; shim.SignalOK(); poller = new Poller(); poller.AddSocket(shim); poller.AddSocket(snapshotSocket); poller.AddTimer(heartbeatTimer); poller.Start(); publisherSocket.Dispose(); snapshotSocket.Dispose(); }
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); }
protected void CreateServer() { switch (_type) { case MQServerType.Response: _serverSocket = _context.CreateResponseSocket(); break; case MQServerType.Publisher: _serverSocket = _context.CreatePublisherSocket(); break; case MQServerType.Router: _serverSocket = _context.CreateRouterSocket(); break; case MQServerType.Stream: _serverSocket = _context.CreateStreamSocket(); break; case MQServerType.Push: _serverSocket = _context.CreatePushSocket(); break; case MQServerType.XPublisher: _serverSocket = _context.CreateXPublisherSocket(); break; default: _serverSocket = _context.CreateResponseSocket(); break; } _serverSocket.Bind("tcp://*:" + _port); }
/// <summary> /// Subscribe To Start Auction /// </summary> public void subscribeToStartAuctionCmd() { // Bind the publisher to the address _publisher = _context.CreatePublisherSocket(); _publisher.Bind(ConfigurationManager.AppSettings["pubAddr"]); // Connect to address for StartAuction and subscribe to the topic - StartAuction var startAuctionSub = _context.CreateSubscriberSocket(); var startAuctionTopic = ConfigurationManager.AppSettings["startAuctionTopic"]; startAuctionSub.Connect(ConfigurationManager.AppSettings["startAuctionAddr"]); startAuctionSub.Subscribe(startAuctionTopic); Console.WriteLine("SUB: " + startAuctionTopic); while (true) { string startAuctionCmd = startAuctionSub.ReceiveString(); Console.WriteLine("REC: " + startAuctionCmd); publishAcknowledgement(startAuctionCmd); // Extract the ID and get the bidders emails string id = MessageParser.parseMessage(startAuctionCmd, "<id>", "</id>"); IDatabase database = DatabaseFacade.GetDatabase(); string[] emails = database.getBidderEmails(id); if (emails != null) { publishNotifyBiddersCommand(id, emails); } publishAuctionStartedEvent(id); } }
public void Sending1000Messages() { // creating two different context and sending 1000 messages int count = 0; ManualResetEvent subReady = new ManualResetEvent(false); Task subTask = Task.Factory.StartNew(() => { using (NetMQContext context = NetMQContext.Create()) { using (var sub = context.CreateSubscriberSocket()) { sub.Bind("pgm://224.0.0.1:5555"); sub.Subscribe(""); subReady.Set(); while (count < 1000) { bool more; byte[] data = sub.Receive(out more); Assert.IsFalse(more); int num = BitConverter.ToInt32(data, 0); Assert.AreEqual(num, count); count++; } } } }); subReady.WaitOne(); Task pubTask = Task.Factory.StartNew(() => { using (NetMQContext context = NetMQContext.Create()) { using (var pub = context.CreatePublisherSocket()) { pub.Connect("pgm://224.0.0.1:5555"); for (int i = 0; i < 1000; i++) { pub.Send(BitConverter.GetBytes(i)); } } } }); pubTask.Wait(); subTask.Wait(); Thread.MemoryBarrier(); Assert.AreEqual(1000, count); }
public void ConnectBothSockets() { using (NetMQContext context = NetMQContext.Create()) { using (var pub = context.CreatePublisherSocket()) { pub.Connect("pgm://224.0.0.1:5555"); using (var sub = context.CreateSubscriberSocket()) { sub.Connect("pgm://224.0.0.1:5555"); sub.Subscribe(""); pub.Send("Hi"); bool more; string message = sub.ReceiveString(out more); Assert.IsFalse(more); Assert.AreEqual("Hi", message); } } } }
public void UseInterface() { var hostEntry = Dns.GetHostEntry(Dns.GetHostName()); string ip = ( from addr in hostEntry.AddressList where addr.AddressFamily == AddressFamily.InterNetwork select addr.ToString() ).FirstOrDefault(); using (NetMQContext context = NetMQContext.Create()) { using (var pub = context.CreatePublisherSocket()) { pub.Connect(string.Format("pgm://{0};224.0.0.1:5555", ip)); using (var sub = context.CreateSubscriberSocket()) { sub.Bind(string.Format("pgm://{0};224.0.0.1:5555", ip)); sub.Subscribe(""); pub.Send("Hi"); bool more; string message = sub.ReceiveString(out more); Assert.IsFalse(more); Assert.AreEqual("Hi", message); } } } }
private void SetupPublisher() { Open(0); _publisherSocket = _context.CreatePublisherSocket(); _publisherSocket.Bind(_configuration.PublisherAddress); }
public Publisher(string address) { _context = NetMQContext.Create(); _socket = _context.CreatePublisherSocket(); _socket.Bind(address); Console.WriteLine("Publisher: bound to {0}", address); }
public void MultipleSubscriptions() { using (NetMQContext contex = NetMQContext.Create()) { using (var pub = contex.CreatePublisherSocket()) { pub.Bind("tcp://127.0.0.1:5002"); using (var sub = contex.CreateSubscriberSocket()) { sub.Connect("tcp://127.0.0.1:5002"); sub.Subscribe("C"); sub.Subscribe("B"); sub.Subscribe("A"); sub.Subscribe("D"); sub.Subscribe("E"); Thread.Sleep(500); sub.Unsubscribe("C"); sub.Unsubscribe("B"); sub.Unsubscribe("A"); sub.Unsubscribe("D"); sub.Unsubscribe("E"); Thread.Sleep(500); } } } }
public void LargeMessage() { using (NetMQContext context = NetMQContext.Create()) { using (var pubSocket = context.CreatePublisherSocket()) { pubSocket.Bind("tcp://127.0.0.1:5556"); using (var subSocket = context.CreateSubscriberSocket()) { subSocket.Connect("tcp://127.0.0.1:5556"); subSocket.Subscribe(""); Thread.Sleep(100); byte[] msg = new byte[300]; pubSocket.Send(msg); byte[] msg2 = subSocket.Receive(); Assert.AreEqual(300, msg2.Length); } } } }
private void createSSocket() { clientS = context.CreatePublisherSocket(); string[] srAddrs = cfg.ServerR.Split(','); foreach (string addr in srAddrs) { clientS.Connect(addr); } }
public void Start(int publishPort) { ctx = NetMQContext.Create(); publishSocket = ctx.CreatePublisherSocket(); publishSocket.Bind("tcp://*:" + publishPort); logger.Info("Message publisher started on port " + publishPort); }
/// <summary> /// Default ctor. /// </summary> public FeedMuxMessageBroker() { context = NetMQContext.Create(); pubSocket = context.CreatePublisherSocket(); pubSocket.Connect(PublisherAddress); pollerCancelled = new ManualResetEvent(false); source = new CancellationTokenSource(); token = source.Token; StartPolling(); }
public void Connect(string givenAddress) { if (IsConnected) { return; } pubSocket = context.CreatePublisherSocket(); pubSocket.Connect(givenAddress); IsConnected = true; }
public void init(string address, int port) { this.address = address; this.port = port; //create context context = NetMQContext.Create(); //create client publisher = context.CreatePublisherSocket(); //connect publisher publisher.Bind("tcp://" + address + ":" + port); }
public void Connect(string givenAddress) { if (IsConnected) { return; } pubSocket = context.CreatePublisherSocket(); // Use connect when working with FitzCore. For direct connection use Bind. //pubSocket.Connect(givenAddress); pubSocket.Bind(givenAddress); IsConnected = true; }
protected override void ConsumerAction() { using (NetMQContext ctx = NetMQContext.Create()) { using (PublisherSocket socket = ctx.CreatePublisherSocket()) { socket.Bind(Address); foreach (NetMQMessage message in Queue.GetConsumingEnumerable()) { socket.SendMessage(message); } } } }
// initialized sprites void Start() { AsyncIO.ForceDotNet.Force(); calImages = new Sprite[10]; calImages[0] = Resources.Load <Sprite>("notargets"); calImages[1] = Resources.Load <Sprite>("targetTL"); calImages[2] = Resources.Load <Sprite>("targetTM"); calImages[3] = Resources.Load <Sprite>("targetTR"); calImages[4] = Resources.Load <Sprite>("targetML"); calImages[5] = Resources.Load <Sprite>("targetMM"); calImages[6] = Resources.Load <Sprite>("targetMR"); calImages[7] = Resources.Load <Sprite>("targetBL"); calImages[8] = Resources.Load <Sprite>("targetBM"); calImages[9] = Resources.Load <Sprite>("targetBR"); calCount = 0; curCount = 0; gameObject.GetComponent <Image> ().sprite = calImages [calCount]; //max coords 1180*564 transX = 0; transY = 0; targetPrefab = GameObject.FindGameObjectWithTag("RaycastTarget"); targetPrefab.SetActive(false); targetPrefab.layer = 2; //ignore raycast layer isVisible = false; AsyncIO.ForceDotNet.Force(); //setup sockets //hangs???? //http://forum.unity3d.com/threads/netmq-basic.298104/ //must compile myself //https://github.com/zeromq/netmq/issues/98 context = NetMQContext.Create(); server = context.CreatePublisherSocket(); server.Bind("tcp://127.0.0.1:5556"); client = context.CreateSubscriberSocket(); client.Connect("tcp://127.0.0.1:5556"); client.Subscribe("coord"); Debug.Log(System.Environment.Version); /*server.SendMore("coord").Send ("200 200"); * string top = client.ReceiveString (); * string message = client.ReceiveString (); * Debug.Log (message); * string[] coord = message.Split (); * transX = int.Parse (coord [0]); * transY = int.Parse (coord [1]);*/ }
public void Start(string configFile) { config = ServiceConfig.FromXml(configFile); log.DebugFormat("Start from {0}", configFile); if (config.PushPull != null) { log.InfoFormat("Starting listening for Pull: {0}", config.PushPull.ListenAddress); NetMQContext ctx1 = NetMQContext.Create(); InitLinks(ctx1, _push_links, config.PushPull, ZmqSocketType.Push); puller = ctx1.CreatePullSocket(); puller.ReceiveReady += this.PullerReceiveReady; puller.Bind(config.PushPull.ListenAddress); this.source_pp = new CancellationTokenSource(); this.token_pp = this.source_pp.Token; Task newTask = Task.Factory.StartNew(this.OnPull, this.token_pp); this.tasks.Add(newTask); } if (config.PubSub != null) { log.InfoFormat("Starting listening for subscriber: {0}", config.PubSub.ListenAddress); NetMQContext ctx2 = NetMQContext.Create(); InitLinks(ctx2, _sub_links, config.PubSub, ZmqSocketType.Sub); foreach (var link in _sub_links) { link.Value.socket.ReceiveReady += SubOnReceiveReady; } publisher = ctx2.CreatePublisherSocket(); publisher.Bind(config.PubSub.ListenAddress); this.source_ps = new CancellationTokenSource(); this.token_ps = this.source_ps.Token; Task newTask = Task.Factory.StartNew(this.OnSubscribe, this.token_ps); this.tasks.Add(newTask); } if (config.ReqRep != null) { log.InfoFormat("Starting listening for Request: {0}", config.ReqRep.ListenAddress); NetMQContext ctx3 = NetMQContext.Create(); //InitLinks(ctx3, _req_links, config.ReqRep, ZmqSocketType.Req); delete by xsw 2014-09-17 responser = ctx3.CreateResponseSocket(); responser.ReceiveReady += this.RepReceiveReady; responser.Bind(config.ReqRep.ListenAddress); this.source_rr = new CancellationTokenSource(); this.token_rr = this.source_rr.Token; Task newTask = Task.Factory.StartNew(this.OnResponse, this.token_rr); this.tasks.Add(newTask); } }
private void SendEvents(String subscriptionUri, String topic, CancellationToken cancellationToken) { using (NetMQContext context = NetMQContext.Create()) { using (NetMQSocket publishSocket = context.CreatePublisherSocket()) { publishSocket.IgnoreErrors = true; publishSocket.Bind(subscriptionUri); Logger.Info("ZeroMQBroker: Bound to subscriptionUri \"{0}\".", subscriptionUri); while (!cancellationToken.IsCancellationRequested) { try { ZeroMQMessage message; if (mQueue.TryTake(out message, TimeSpan.FromSeconds(1))) { Logger.Debug("ZeroMQBroker: Sending -> {0}", message.ToString()); publishSocket.SendMore(message.Topic); publishSocket.SendMore(message.Client); publishSocket.Send(message.Content); } } catch (OperationCanceledException) { // We have been asked to cancel operation break; } catch (Exception ex) { Logger.Error("ZeroMQBroker: Error sending message.", ex); } } // Close socket publishSocket.Close(); } context.Terminate(); } }
private void start(CancellationToken token, string address, TaskCompletionSource <bool> ready) { using (var socket = _context.CreatePublisherSocket()) { socket.Bind(address); ready.SetResult(true); long count = 0; while (token.IsCancellationRequested == false) { count++; Task.Delay(TimeSpan.FromSeconds(1), token).Wait(token); var item = getNewsItem(); var topicBytes = Encoding.ASCII.GetBytes(item.Item1); socket.Send(topicBytes, topicBytes.Length, sendMore: true); string news = string.Format("{0}: {1}", count, item.Item2); byte[] bytes = Encoding.ASCII.GetBytes(news); socket.Send(bytes); } } }
public void TestPubSub() { // Create publisher and bind it to a localhost address and port PublisherSocket publisher = _context.CreatePublisherSocket(); publisher.Bind("tcp://127.0.0.1:9999"); // Allow time to bind Thread.Sleep(1000); // Create a thread to subscribe to the published message Thread subscriber = new Thread(new ThreadStart(subscribe)); subscriber.Start(); // Publish a test message publisher.Send("Test"); Thread.Sleep(1000); // Kill the thread subscriber.Abort(); }
/// <summary> /// Starts the publishing and request servers. /// </summary> public void StartServer() { if (!ServerRunning) { _context = NetMQContext.Create(); //the publisher socket _pubSocket = _context.CreatePublisherSocket(); _pubSocket.Bind("tcp://*:" + PublisherPort); //the request socket _reqSocket = _context.CreateSocket(ZmqSocketType.Rep); _reqSocket.Bind("tcp://*:" + RequestPort); _reqSocket.ReceiveReady += _reqSocket_ReceiveReady; _poller = new Poller(new[] { _reqSocket }); Task.Factory.StartNew(_poller.Start, TaskCreationOptions.LongRunning); } ServerRunning = true; }
//! //! sender function, sending messages in sendMessageQueue to server (executed in separate thread) //! public void publisher() { //create NetMQ context NetMQContext ctx = NetMQContext.Create(); NetMQ.Sockets.PublisherSocket sender = ctx.CreatePublisherSocket(); sender.Connect("tcp://" + VPETSettings.Instance.serverIP + ":5557"); while (isRunning) { if (sendMessageQueue.Count > 0) { // Debug.Log("Publisher: " + sendMessageQueue[0] as string); sender.Send("client " + sendMessageQueue[0] as string); sendMessageQueue.RemoveAt(0); } } sender.Disconnect("tcp://" + VPETSettings.Instance.serverIP + ":5557"); sender.Close(); }
public void SetPgmSettings() { const int MegaBit = 1024; const int MegaByte = 1024; using (NetMQContext context = NetMQContext.Create()) { using (var pub = context.CreatePublisherSocket()) { pub.Options.MulticastHops = 2; pub.Options.MulticastRate = 40 * MegaBit; // 40 megabit pub.Options.MulticastRecoveryInterval = TimeSpan.FromMinutes(10); pub.Options.SendBuffer = MegaByte * 10; // 10 megabyte pub.Connect("pgm://224.0.0.1:5555"); using (var sub = context.CreateSubscriberSocket()) { sub.Options.ReceivevBuffer = MegaByte * 10; sub.Bind("pgm://224.0.0.1:5555"); sub.Subscribe(""); pub.Send("Hi"); bool more; string message = sub.ReceiveString(out more); Assert.IsFalse(more); Assert.AreEqual("Hi", message); Assert.AreEqual(2, pub.Options.MulticastHops); Assert.AreEqual(40 * MegaBit, pub.Options.MulticastRate); Assert.AreEqual(TimeSpan.FromMinutes(10), pub.Options.MulticastRecoveryInterval); Assert.AreEqual(MegaByte * 10, pub.Options.SendBuffer); Assert.AreEqual(MegaByte * 10, sub.Options.ReceivevBuffer); } } } }
public void MultipleLargeMessages() { byte[] largeMessage = new byte[12000]; for (int i = 0; i < 12000; i++) { largeMessage[i] = (byte)(i % 256); } using (NetMQContext context = NetMQContext.Create()) { using (NetMQSocket pubSocket = context.CreatePublisherSocket()) { pubSocket.Bind("tcp://127.0.0.1:5558"); using (NetMQSocket subSocket = context.CreateSubscriberSocket()) { subSocket.Connect("tcp://127.0.0.1:5558"); subSocket.Subscribe(""); Thread.Sleep(1000); pubSocket.Send(""); subSocket.Receive(); for (int i = 0; i < 100; i++) { pubSocket.Send(largeMessage); byte[] recvMesage = subSocket.Receive(); for (int j = 0; j < 12000; j++) { Assert.AreEqual(largeMessage[j], recvMesage[j]); } } } } } }