public void Start() { if (context == null) { context = NetMQContext.Create(); publisher = context.CreatePublisherSocket(); publisher.Bind("tcp://*:5252"); receiver = context.CreatePullSocket(); receiver.Bind("tcp://*:5253"); // Start listening.. Task.Run(() => { try { while (!tokenSource.IsCancellationRequested) { var message = receiver.ReceiveString(); var command = Serialization.DeserializeEnvelope <ContractMarker>(message); commandReceivedSubject.OnNext(command); } } catch (Exception ex) { Tracer.Error(ex); throw; } }); } }
private NetMQSocket GetInboundSocket(NetMQContext context) { NetMQSocket socket; switch (Connection.Pattern) { case MessagePattern.FireAndForget: socket = context.CreatePullSocket(); socket.Bind(Connection.Address); break; case MessagePattern.RequestResponse: socket = context.CreateResponseSocket(); socket.Bind(Connection.Address); break; case MessagePattern.PublishSubscribe: var subSocket = context.CreateSubscriberSocket(); subSocket.SubscribeToAnyTopic(); subSocket.Connect(Connection.Address); socket = subSocket; break; default: throw new Exception($"Cannot create an inbound socket for pattern {Connection.Pattern}"); } return(socket); }
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); }
/// <summary> /// Initializes a new instance of the <see cref="StreamerDevice"/> 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 StreamerDevice(NetMQContext context, Poller poller, string frontendBindAddress, string backendBindAddress, DeviceMode mode = DeviceMode.Threaded) : base(poller, context.CreatePullSocket(), context.CreatePushSocket(), mode) { FrontendSetup.Bind(frontendBindAddress); BackendSetup.Bind(backendBindAddress); }
public StreamerDevice(NetMQContext context, INetMQPoller poller, string frontendBindAddress, string backendBindAddress, DeviceMode mode = DeviceMode.Threaded) : base(poller, context.CreatePullSocket(), context.CreatePushSocket(), mode) { FrontendSetup.Bind(frontendBindAddress); BackendSetup.Bind(backendBindAddress); }
public Server(string address) { _mainThread = new TaskThread("执行", MainLoop); _sendThread = new TaskThread("发送", OnSend); _receThread = new TaskThread("接收", OnReceive); Address = address; _netMqContext = NetMQContext.Create(); _pullSocket = _netMqContext.CreatePullSocket(); _pushSocket = _netMqContext.CreatePushSocket(); Current = this; }
public void Start(int listenPort) { ctx = NetMQContext.Create(); responseSocket = ctx.CreatePullSocket(); responseSocket.Bind("tcp://*:" + listenPort); isRunning = true; listenThread = new Thread(ListenForMessages); listenThread.Name = "ClientMessageListenThread"; listenThread.Start(); logger.Info("Client message puller has started listening on port " + listenPort); }
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); } }
public static void Main(string[] args) { // Task Worker // Connects PULL socket to tcp://localhost:5557 // collects workload for socket from Ventilator via that socket // Connects PUSH socket to tcp://localhost:5558 // Sends results to Sink via that socket Console.WriteLine("====== WORKER ======"); using (NetMQContext ctx = NetMQContext.Create()) { //socket to receive messages on using (var receiver = ctx.CreatePullSocket()) { receiver.Connect("tcp://localhost:5557"); //socket to send messages on using (var sender = ctx.CreatePushSocket()) { sender.Connect("tcp://localhost:5558"); //process tasks forever while (true) { //workload from the vetilator is a simple delay //to simulate some work being done, see //Ventilator.csproj Proram.cs for the workload sent //In real life some more meaningful work would be done string workload = receiver.ReceiveString(); //simulate some work being done Thread.Sleep(int.Parse(workload)); //send results to sink, sink just needs to know worker //is done, message content is not important, just the precence of //a message means worker is done. //See Sink.csproj Proram.cs Console.WriteLine("Sending to Sink"); sender.Send(string.Empty); } } } } }
public void Run() { Task.Run(() => { using (NetMQContext context = NetMQContext.Create()) { //socket to receive messages on using (var receiver = context.CreatePullSocket()) { receiver.Connect("tcp://127.0.0.1:5557"); //socket to send messages on using (var sender = context.CreatePushSocket()) { sender.Connect("tcp://127.0.0.1:5558"); //process tasks forever while (true) { //workload from the vetilator is a simple delay //to simulate some work being done, see //Ventilator.csproj Program.cs for the workload sent //In real life some more meaningful work would be done string workload = receiver.ReceiveString(); var person = JsonConvert.DeserializeObject <Person>(workload); //JArray ja = JArray.Parse(workload); Console.WriteLine("Person {Id:" + person.Id + ",Name:" + person.Name + ",BirthDay:" + person.BirthDay + ",Address:{Line1:" + person.Address.Line1 + ",Line2:" + person.Address.Line2 + "}}"); Console.WriteLine("Sending to Sink:" + person.Id); sender.SendFrame(person.Id + ""); //sender.SendFrame("liuwq" + DateTime.Now); } //simulate some work being done //Thread.Sleep(int.Parse(workload)); } } } }); }
private static void Serve() { Console.WriteLine("====== Server ======"); InitRegions(); using (NetMQContext ctx = NetMQContext.Create()) { using (var receiver = ctx.CreatePullSocket()) { receiver.Bind(bindAddress); while (true) { string cmd = receiver.ReceiveString(); Dump(cmd); } } } }
public static void Main(string[] args) { // Task Sink // Bindd PULL socket to tcp://localhost:5558 // Collects results from workers via that socket Console.WriteLine("====== SINK ======"); using (NetMQContext ctx = NetMQContext.Create()) { //socket to receive messages on using (var receiver = ctx.CreatePullSocket()) { receiver.Bind("tcp://localhost:5558"); //wait for start of batch (see Ventilator.csproj Program.cs) var startOfBatchTrigger = receiver.ReceiveString(); Console.WriteLine("Seen start of batch"); //Start our clock now Stopwatch watch = new Stopwatch(); watch.Start(); for (int taskNumber = 0; taskNumber < 100; taskNumber++) { var workerDoneTrigger = receiver.ReceiveString(); if (taskNumber % 10 == 0) { Console.Write(":"); } else { Console.Write("."); } } watch.Stop(); //Calculate and report duration of batch Console.WriteLine(); Console.WriteLine("Total elapsed time {0} msec", watch.ElapsedMilliseconds); Console.ReadLine(); } } }
private void start(CancellationToken token, string source, string sink, TaskCompletionSource <bool> ready) { using (var sourceSocket = _context.CreatePullSocket()) using (var sinkSocket = _context.CreatePushSocket()) { sourceSocket.Connect(source); sinkSocket.Connect(sink); ready.SetResult(true); while (token.IsCancellationRequested == false) { var messageBytes = sourceSocket.Receive(); var message = Encoding.ASCII.GetString(messageBytes); Console.WriteLine("[{0}] Processing task {1}", _id, message); Task.Delay(50, token).Wait(token); sinkSocket.Send(messageBytes); } } }
public void EmptyMessage() { using (NetMQContext context = NetMQContext.Create()) { using (var pullSocket = context.CreatePullSocket()) { pullSocket.Bind("tcp://127.0.0.1:5004"); using (var pushSocket = context.CreatePushSocket()) { pushSocket.Connect("tcp://127.0.0.1:5004"); pushSocket.Send(new byte[300]); bool more; byte[] m = pullSocket.Receive(out more); Assert.AreEqual(300, m.Length); } } } }
public void SimplePushPull() { using (NetMQContext context = NetMQContext.Create()) { using (var pullSocket = context.CreatePullSocket()) { pullSocket.Bind("tcp://127.0.0.1:5004"); using (var pushSocket = context.CreatePushSocket()) { pushSocket.Connect("tcp://127.0.0.1:5004"); pushSocket.Send("hello"); bool more; string m = pullSocket.ReceiveString(out more); Assert.AreEqual("hello", m); } } } }
private void start(CancellationToken token, string address, TaskCompletionSource <bool> ready) { using (var socket = _context.CreatePullSocket()) { socket.Bind(address); ready.SetResult(true); int received = 0; while (token.IsCancellationRequested == false && received < _numberToReceive) { var bytes = socket.Receive(); received++; var taskId = Encoding.ASCII.GetString(bytes); Console.WriteLine("[{0}] Received - {1}", _id, taskId); } if (received == _numberToReceive) { Console.WriteLine("[{0}] Received {1} results.", _id, _numberToReceive); } } }
private void ListenSocket(object state) { var cancellationToken = (CancellationToken)state; try { using (var socket = _context.CreatePullSocket()) { socket.Bind(_bindAddress); Console.WriteLine("PullReceiver: bound to {0}", _bindAddress); byte[] buffer; while (_disposeCount == 0 && !cancellationToken.IsCancellationRequested) { buffer = new Func <byte[]>(() => socket.Receive()).CaptureMqExceptions <AgainException, byte[]>(); if (buffer == null) { continue; } var message = buffer.DeserializeMessage(); Console.WriteLine("Msg recd on {1:HH:mm:ss.fff}: {0}", message, DateTime.UtcNow); // TODO : process message [...] } } } catch (TerminatingException) { Debug.WriteLine(string.Format("TerminatingException: auto-disposing {0}...", this.GetType().Name)); ((IDisposable)this).Dispose(); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } Debug.WriteLine("End of reception."); }
protected override PullSocket CreateConsumerSocket(NetMQContext context) { return context.CreatePullSocket(); }
static void Main(string[] args) { // Task Sink // Bindd PULL socket to tcp://localhost:5558 // Collects results from workers via that socket Console.WriteLine("====== SINK ======"); using (NetMQContext ctx = NetMQContext.Create()) { //socket to receive messages on using (var receiver = ctx.CreatePullSocket()) { receiver.Bind("tcp://10.151.12.9:5558"); //wait for start of batch (see Ventilator.csproj Program.cs) byte[] startOfBatchTrigger = receiver.Receive(); Console.WriteLine("Seen start of batch"); //Start our clock now Stopwatch watch = new Stopwatch(); watch.Start(); //for (int taskNumber = 0; taskNumber < 100; taskNumber++) //{ // var workerDoneTrigger = receiver.ReceiveString(); // if (taskNumber % 10 == 0) // { // Console.Write(":"); // } // else // { // Console.Write("."); // } //} //watch.Stop(); ////Calculate and report duration of batch //Console.WriteLine(); //Console.WriteLine("Total elapsed time {0} msec", watch.ElapsedMilliseconds); //Console.WriteLine(receiver.Receive()); Console.WriteLine(BitConverter.ToInt32(startOfBatchTrigger, 0)); int i = 0; for (i = 0; i < BitConverter.ToInt32(startOfBatchTrigger, 0); i++) { //string name = receiver.ReceiveString(); byte[] input; input = receiver.Receive(); int l = input.Length; byte[] num = new byte[4]; System.Buffer.BlockCopy(input, l - 4, num, 0, 4); int len = BitConverter.ToInt32(num, 0); Console.WriteLine(len); byte[] sendI = new byte[l - len - 4]; System.Buffer.BlockCopy(input, 0, sendI, 0, l - len - 4); byte[] nameb = new byte[len]; System.Buffer.BlockCopy(input, l - len - 4, nameb, 0, len); String name = GetString(nameb); Image bw = byteArrayToImage(sendI); SaveFile(bw, name); Console.WriteLine("Saved " + name); } watch.Stop(); //Calculate and report duration of batch Console.WriteLine(); Console.WriteLine("Total elapsed time {0} msec", watch.ElapsedMilliseconds); Console.ReadLine(); } } }
private void initServerThr() { poller = new Poller(); using (NetMQContext context = NetMQContext.Create()) { using (var receiver = context.CreatePullSocket()) using (var publisher = context.CreatePublisherSocket()) { try { receiver.Bind(cfg.ServerR); publisher.Bind(cfg.ServerS); } catch (Exception ex) { DCLogger.LogError("Exception in ServerThr's bind work:{0}", ex.Message); } //r & s receiver.ReceiveReady += (sender, eventArgs) => { try { List <byte[]> dataLst = new List <byte[]>(); receiver.ReceiveMultipartBytes(ref dataLst, 2); //DCLogger.LogInfo("Received:{0}", Global.Encoding.GetString(dataLst[0])); if (dataLst.Count != 2) { return; } publisher.SendMultipartBytes(dataLst[0], dataLst[1]); //DCLogger.LogInfo("Sended:{0}", Global.Encoding.GetString(dataLst[0])); } catch (Exception ex) { DCLogger.LogError("Exception in ServerThr's exchange work:{0}", ex.Message); } }; poller.AddSocket(receiver); // send heartbeat every two seconds NetMQTimer heartbeatTimer = new NetMQTimer(30000); poller.AddTimer(heartbeatTimer); heartbeatTimer.Elapsed += (sender, eventArgs) => { try { publisher.SendMultipartBytes(Global.DC_CTRL_HB, BitConverter.GetBytes(DateTime.Now.Ticks)); DCLogger.LogInfo("Server's HeartBeat sended:{0}", DateTime.Now); } catch (Exception ex) { DCLogger.LogError("Exception in ServerThr's heartbeat work:{0}", ex.Message); } }; poller.PollTillCancelled(); } } }
protected override PullSocket CreateWorkerSocket(NetMQContext context) { return(context.CreatePullSocket()); }
private void ReceiveEvents(String submissionUri, String topic, CancellationToken cancellationToken) { using (NetMQContext context = NetMQContext.Create()) { using (NetMQSocket pullSocket = context.CreatePullSocket()) { pullSocket.IgnoreErrors = true; pullSocket.Bind(submissionUri); Logger.Info("ZeroMQBroker: Bound to submissionUri \"{0}\".", submissionUri); // Eventhandler delegate to handle receiving messages pullSocket.ReceiveReady += (sender, args) => { try { if (args.ReceiveReady) { // Recieve and relay NetMQMessage netMQmessage = args.Socket.ReceiveMessage(); // Recieve the message ZeroMQMessage message = new ZeroMQMessage() { Topic = netMQmessage.Pop().ConvertToString(), Client = netMQmessage.Pop().ConvertToString(), Content = netMQmessage.Pop().ConvertToString() }; Logger.Debug("ZeroMQBroker: Received -> {0}", message.ToString()); mQueue.Add(message); // ZeroMQBroker relays multiple topics, verify if the message was meant for the current client if (String.Equals(topic, message.Topic, StringComparison.OrdinalIgnoreCase)) { XmlCacheEvent cacheEvent = XmlCacheEvent.FromXml(message.Content); if (cacheEvent != null) { OnCacheEvent(cacheEvent.CacheRegion, cacheEvent.Key, cacheEvent.EventType); } } } } catch (OperationCanceledException) { // We have been asked to cancel operation return; } catch (Exception ex) { Logger.Error("ZeroMQBroker: Error receiving message.", ex); } }; while (!cancellationToken.IsCancellationRequested) { try { pullSocket.Poll(TimeSpan.FromSeconds(1)); } catch (OperationCanceledException) { // We have been asked to cancel operation break; } catch (Exception ex) { Logger.Error("ZeroMQBroker: Error polling for messages.", ex); } } // Close socket pullSocket.Close(); } context.Terminate(); } }
public ZeroNotificationDequeue() { _context = NetMQContext.Create(); _client = _context.CreatePullSocket(); _client.Bind(QueueAddress); }
public void Run() { using (var socket = context.CreatePullSocket()) { socket.Options.Linger = TimeSpan.Zero; socket.Bind(clientAddress.ZmqAddress + ":" + GlobalConstants.TcpIpPort.Notification); while (!stopRunning) { var notification = socket.ReceiveNetworkMsg(TimeSpan.FromSeconds(1)); if (notification == null) { continue; } switch (notification.Type) { case NetworkMessageType.EventBusNotification: { var eventNotification = (EventBusNotification)notification; if (eventNotification.SessionId == sessionId) { NewDomainEventAvailable(eventNotification.NewEvent); } break; } case NetworkMessageType.PatientAddedNotification: { var patientAddedNotification = (PatientAddedNotification)notification; if (patientAddedNotification.SessionId == sessionId) { NewPatientAvailable(patientAddedNotification.Patient); } break; } case NetworkMessageType.PatientUpdatedNotification: { var patientUpdatedNotification = (PatientAddedNotification)notification; if (patientUpdatedNotification.SessionId == sessionId) { UpdatedPatientAvailable(patientUpdatedNotification.Patient); } break; } case NetworkMessageType.TherapyPlaceTypeAddedNotification: { var therpyPlaceTypeAddedNotification = (TherapyPlaceTypeAddedNotification)notification; if (therpyPlaceTypeAddedNotification.SessionId == sessionId) { NewTherapyPlaceTypeAvailable(therpyPlaceTypeAddedNotification.TherapyPlaceType); } break; } case NetworkMessageType.TherapyPlaceTypeUpdatedNotification: { var therpyPlaceTypeUpdatedNotification = (TherapyPlaceTypeUpdatedNotification)notification; if (therpyPlaceTypeUpdatedNotification.SessionId == sessionId) { UpdatedTherapyPlaceTypeAvailable(therpyPlaceTypeUpdatedNotification.TherapyPlaceType); } break; } case NetworkMessageType.LabelAddedNotification: { var labelAddedNotification = (LabelAddedNotification)notification; if (labelAddedNotification.SessionId == sessionId) { NewLabelAvailable(labelAddedNotification.Label); } break; } case NetworkMessageType.LabelUpdatedNotification: { var labelUpdatedNotification = (LabelUpdatedNotification)notification; if (labelUpdatedNotification.SessionId == sessionId) { UpdatedLabelAvailable(labelUpdatedNotification.Label); } break; } default: throw new ArgumentException(); } } } }
static void Main(string[] args) { // Task Worker // Connects PULL socket to tcp://localhost:5557 // collects workload for socket from Ventilator via that socket // Connects PUSH socket to tcp://localhost:5558 // Sends results to Sink via that socket Console.WriteLine("====== WORKER ======"); using (NetMQContext ctx = NetMQContext.Create()) { //socket to receive messages on using (var receiver = ctx.CreatePullSocket()) { receiver.Connect("tcp://10.151.12.9:5557"); //socket to send messages on using (var sender = ctx.CreatePushSocket()) { sender.Connect("tcp://10.151.12.9:5558"); //process tasks forever while (true) { ////workload from the vetilator is a simple delay ////to simulate some work being done, see ////Ventilator.csproj Proram.cs for the workload sent ////In real life some more meaningful work would be done //string workload = receiver.ReceiveString(); ////simulate some work being done //Thread.Sleep(int.Parse(workload)); ////send results to sink, sink just needs to know worker ////is done, message content is not important, just the precence of ////a message means worker is done. ////See Sink.csproj Proram.cs //sender.Send(receiver.Receive()); byte[] input = receiver.Receive(); int i = input.Length; //Console.WriteLine(i); byte[] num = new byte[4]; System.Buffer.BlockCopy(input, i - 4, num, 0, 4); int len = BitConverter.ToInt32(num, 0); Console.WriteLine(len); byte[] nameb = new byte[len]; System.Buffer.BlockCopy(input, i - len - 4, nameb, 0, len); byte[] sendI = new byte[i - len - 4]; System.Buffer.BlockCopy(input, 0, sendI, 0, i - len - 4); //Console.WriteLine(sendI.Length); byte[] output = ToBW(sendI); byte[] sendM = new byte[output.Length + len + 4]; System.Buffer.BlockCopy(output, 0, sendM, 0, output.Length); System.Buffer.BlockCopy(nameb, 0, sendM, output.Length, len); System.Buffer.BlockCopy(num, 0, sendM, output.Length + len, 4); sender.Send(sendM); Console.WriteLine("Sending to Sink"); //Image bw = byteArrayToImage(output); //SaveFile(bw); } } } } }
public GatewayServer() : base(new GatewayReceiveFilterFactory()) // 7 parts but 8 separators { _netMqContext = NetMQContext.Create(); _pullSocket = _netMqContext.CreatePullSocket(); _pushSocket = _netMqContext.CreatePushSocket(); }