void CreateServer() { switch (_type) { case ServerType.Response: _serverSocket = _context.CreateResponseSocket(); break; case ServerType.Pub: _serverSocket = _context.CreatePushSocket(); break; case ServerType.Router: _serverSocket = _context.CreateRouterSocket(); break; case ServerType.Stream: _serverSocket = _context.CreateStreamSocket(); break; case ServerType.Push: _serverSocket = _context.CreatePushSocket(); break; case ServerType.XPub: _serverSocket = _context.CreateXPublisherSocket(); break; default: _serverSocket = _context.CreateResponseSocket(); break; } _serverSocket.Bind("tcp://*:" + _port); Task.Factory.StartNew(() => AsyncRead(_serverSocket), TaskCreationOptions.LongRunning); }
public static void Main(string[] args) { // Task Ventilator // Binds PUSH socket to tcp://localhost:5557 // Sends batch of tasks to workers via that socket Console.WriteLine("====== VENTILATOR ======"); using (NetMQContext ctx = NetMQContext.Create()) { //socket to send messages on using (var sender = ctx.CreatePushSocket()) { sender.Bind("tcp://*:5557"); using (var sink = ctx.CreatePushSocket()) { sink.Connect("tcp://localhost:5558"); Console.WriteLine("Press enter when worker are ready"); Console.ReadLine(); //the first message it "0" and signals start of batch //see the Sink.csproj Program.cs file for where this is used Console.WriteLine("Sending start of batch to Sink"); sink.Send("0"); Console.WriteLine("Sending tasks to workers"); //initialise random number generator Random rand = new Random(0); //expected costs in Ms int totalMs = 0; //send 100 tasks (workload for tasks, is just some random sleep time that //the workers can perform, in real life each work would do more than sleep for (int taskNumber = 0; taskNumber < 100; taskNumber++) { //Random workload from 1 to 100 msec int workload = rand.Next(0, 100); totalMs += workload; Console.WriteLine("Workload : {0}", workload); sender.Send(workload.ToString()); } Console.WriteLine("Total expected cost : {0} msec", totalMs); Console.WriteLine("Press Enter to quit"); Console.ReadLine(); } } } }
public void Start() { if (!ServerSpecified) { return; } if (context == null) { context = NetMQContext.Create(); subscriber = context.CreateSubscriberSocket(); subscriber.Connect("tcp://127.0.0.1:5252"); subscriber.Subscribe(String.Empty); sender = context.CreatePushSocket(); sender.Connect("tcp://127.0.0.1:5253"); // Start listening.. Task.Run(() => { while (!tokenSource.IsCancellationRequested) { var message = subscriber.ReceiveString(); var eventObject = Serialization.DeserializeEnvelope <ContractMarker>(message); eventReceivedSubject.OnNext(eventObject); } }); } }
//! //! sender function, sending messages in sendMessageQueue to katana server (executed in separate thread) //! public void sendKatana() { //create NetMQ context NetMQContext ctx = NetMQContext.Create(); NetMQ.Sockets.PushSocket katanaSender = ctx.CreatePushSocket(); katanaSender.Connect("tcp://" + VPETSettings.Instance.serverIP + ":5555"); //using (NetMQ.Poller poller = new NetMQ.Poller(katanaSender)) //{ while (isRunning) { if (katanaSendMessageQueue.Count > 0) { // Debug.Log(katanaSendMessageQueue[0] as string); try { katanaSender.Send(katanaSendMessageQueue[0] as string, true); // TODO: note added true argument to not wait } catch { Debug.Log("Failed katanaSenMessage"); } katanaSendMessageQueue.RemoveAt(0); } } //} katanaSender.Disconnect("tcp://" + VPETSettings.Instance.serverIP + ":5555"); katanaSender.Close(); }
/// <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); }
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); }
public PushClient(string address) { _context = NetMQContext.Create(); _socket = _context.CreatePushSocket(); _socket.Connect(address); Console.WriteLine("PushClient: connected to {0}", address); }
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); }
public ZeroNotificationEnqueue() { _context = NetMQContext.Create(); _poller = new Poller(); _client = _context.CreatePushSocket(); _client.Connect(QueueAddress); _scheduler = new NetMQScheduler(_context, _poller); Task.Factory.StartNew(_poller.PollTillCancelled, TaskCreationOptions.LongRunning); }
private void createSSocket() { clientS = context.CreatePushSocket(); string[] srAddrs = cfg.ServerR.Split(','); foreach (string addr in srAddrs) { clientS.Connect(addr); } }
public void Start(string serverIpAddress, int serverPort) { ctx = NetMQContext.Create(); pushSocket = ctx.CreatePushSocket(); string serverAddress = string.Format("tcp://{0}:{1}", serverIpAddress, serverPort); pushSocket.Connect(serverAddress); }
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; }
private static void Client(string cmd) { Console.WriteLine("====== CLient ======"); using (NetMQContext ctx = NetMQContext.Create()) { using (var sender = ctx.CreatePushSocket()) { sender.Connect(connectAddress); sender.Send(cmd); } } }
public void Send(TData request) { using (var socket = _context.CreatePushSocket()) { socket.Bind(_bindEndPoint); var envelope = new NetMQFrame(Encoding.UTF8.GetBytes(request.ToString())); var body = new NetMQFrame(request.ToByteArray()); var msq = new NetMQMessage(); msq.Append(envelope); msq.Append(body); socket.SendMessage(msq); } }
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 void SendEvents(String submissionUri, CancellationToken cancellationToken) { using (NetMQContext context = NetMQContext.Create()) { using (NetMQSocket pushSocket = context.CreatePushSocket()) { pushSocket.IgnoreErrors = true; pushSocket.Connect(submissionUri); Logger.Info("ZeroMQCache: Connected to submissionUri \"{0}\".", submissionUri); while (!cancellationToken.IsCancellationRequested) { try { ZeroMQMessage message; if (mQueue.TryTake(out message, TimeSpan.FromSeconds(1))) { Logger.Debug("ZeroMQCache: Sending -> {0}", message.ToString()); pushSocket.SendMore(message.Topic); pushSocket.SendMore(message.Client); pushSocket.Send(message.Content); } } catch (OperationCanceledException) { // We have been asked to cancel operation break; } catch (Exception ex) { Logger.Error("ZeroMQCache: Error sending message.", ex); } } // Close socket pushSocket.Close(); } context.Terminate(); } }
private void start(CancellationToken token, string address, TaskCompletionSource <bool> ready) { using (var socket = _context.CreatePushSocket()) { socket.Bind(address); ready.SetResult(true); long count = 0; while (token.IsCancellationRequested == false && count < _numberToPush) { count++; //Task.Delay(TimeSpan.FromSeconds(1), token).Wait(token); var item = count.ToString(CultureInfo.InvariantCulture); var bytes = Encoding.ASCII.GetBytes(item); socket.Send(bytes); } Console.WriteLine("[Source {0}] Pushed {1} tasks.", _id, count); } }
public void Message(string cmd) { if (dumperAddress == null) { log.Warn("empty DumperAddress config, ignoring: " + cmd); return; } try { using (var requestSocket = netMQContext.CreatePushSocket()) { requestSocket.Connect(dumperAddress); requestSocket.Send(cmd); } } catch (Exception e) { log.Error("error on dumping", e); } }
//! //! sender function, sending messages in sendMessageQueue to katana server (executed in separate thread) //! public void sendKatana() { //create NetMQ context NetMQContext ctx = NetMQContext.Create(); NetMQ.Sockets.PushSocket katanaSender = ctx.CreatePushSocket(); katanaSender.Connect("tcp://" + VPETSettings.Instance.serverIP + ":5555"); while (isRunning) { if (katanaSendMessageQueue.Count > 0) { // Debug.Log("Katana: " + katanaSendMessageQueue[0] as string); katanaSender.Send(katanaSendMessageQueue[0] as string); katanaSendMessageQueue.RemoveAt(0); } } katanaSender.Disconnect("tcp://" + VPETSettings.Instance.serverIP + ":5555"); katanaSender.Close(); }
private static void SendDumperMessage(NetMQContext mqContext, string fileName, long id) { try { var dumperAddress = ConfigurationManager.AppSettings["DumperAddress"]; if (!string.IsNullOrEmpty(dumperAddress)) { using (var sender = mqContext.CreatePushSocket()) { sender.Connect(dumperAddress); sender.Send("source " + fileName + " " + id); } } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } }
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 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); } } } }
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 Run() { IsRunning = true; using (var socket = context.CreatePushSocket()) { socket.Options.Linger = TimeSpan.Zero; socket.Connect(clientAddress.ZmqAddress + ":" + GlobalConstants.TcpIpPort.Notification); while (!stopRunning) { var nextNotification = notificationQueue.TimeoutTake(); if (nextNotification == null) { continue; } NetworkMessageBase outMsg; switch (nextNotification.NotificationType) { case NetworkMessageType.EventBusNotification: { var eventNotificationObject = (EventNotificationObject)nextNotification; outMsg = new EventBusNotification(eventNotificationObject.DomainEvent, sessionId); break; } case NetworkMessageType.PatientAddedNotification: { var patientAddedNotificationObject = (PatientAddedNotificationObject)nextNotification; outMsg = new PatientAddedNotification(patientAddedNotificationObject.Patient, sessionId); break; } case NetworkMessageType.PatientUpdatedNotification: { var patientUpdatedNotificationObject = (PatientUpdatedNotificationObject)nextNotification; outMsg = new PatientAddedNotification(patientUpdatedNotificationObject.Patient, sessionId); break; } case NetworkMessageType.TherapyPlaceTypeAddedNotification: { var therapyPlaceTypeAddedNotificationObject = (TherpyPlaceTypeAddedNotificationObject)nextNotification; outMsg = new TherapyPlaceTypeAddedNotification(therapyPlaceTypeAddedNotificationObject.TherapyPlaceType, sessionId); break; } case NetworkMessageType.TherapyPlaceTypeUpdatedNotification: { var therapyPlaceTypeUpdatedNotificationObject = (TherpyPlaceTypeUpdatedNotificationObject)nextNotification; outMsg = new TherapyPlaceTypeUpdatedNotification(therapyPlaceTypeUpdatedNotificationObject.TherapyPlaceType, sessionId); break; } default: throw new ArgumentException(); } socket.SendNetworkMsg(outMsg); } } notificationQueue.Dispose(); // It's easier to do this here than in the ThreadCollection IsRunning = false; }
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); } } } } }
protected override PushSocket CreateProducerSocket(NetMQContext context) { return context.CreatePushSocket(); }
public GatewayServer() : base(new GatewayReceiveFilterFactory()) // 7 parts but 8 separators { _netMqContext = NetMQContext.Create(); _pullSocket = _netMqContext.CreatePullSocket(); _pushSocket = _netMqContext.CreatePushSocket(); }
static void Main(string[] args) { // Task Ventilator // Binds PUSH socket to tcp://localhost:5557 // Sends batch of tasks to workers via that socket Console.WriteLine("====== VENTILATOR ======"); using (NetMQContext ctx = NetMQContext.Create()) { //socket to send messages on using (var sender = ctx.CreatePushSocket()) { sender.Bind("tcp://*:5557"); using (var sink = ctx.CreatePushSocket()) { sink.Connect("tcp://10.151.12.9:5558"); Console.WriteLine("Press enter when worker are ready"); Console.ReadLine(); //the first message it "0" and signals start of batch //see the Sink.csproj Program.cs file for where this is used //Console.WriteLine("Sending start of batch to Sink"); //sink.Send("0"); //Console.WriteLine("Sending tasks to workers"); ////initialise random number generator //Random rand = new Random(0); ////expected costs in Ms //int totalMs = 0; ////send 100 tasks (workload for tasks, is just some random sleep time that ////the workers can perform, in real life each work would do more than sleep //for (int taskNumber = 0; taskNumber < 100; taskNumber++) //{ // //Random workload from 1 to 100 msec // int workload = rand.Next(0, 100); // totalMs += workload; // Console.WriteLine("Workload : {0}", workload); // sender.Send(workload.ToString()); //} //Console.WriteLine("Total expected cost : {0} msec", totalMs); int count = 0; string name; byte[] nameb; int len; byte[] image; byte[] num; byte[] sendM; string[] filePaths = Directory.GetFiles("C:\\cygwin64\\home\\user\\coba\\SISTER\\", "*.jpg"); count += filePaths.Length; filePaths = Directory.GetFiles("C:\\cygwin64\\home\\user\\coba\\SISTER\\", "*.png"); count += filePaths.Length; Console.WriteLine(count); Console.WriteLine("Sending start of batch to Sink"); sink.Send(BitConverter.GetBytes(count)); Console.WriteLine("Sending tasks to workers"); int i = 0; for (i = 0; i < filePaths.Length; i++) { name = filePaths[i].Replace("C:\\cygwin64\\home\\user\\coba\\SISTER\\", ""); nameb = GetBytes(name); len = nameb.Length; num = BitConverter.GetBytes(len); image = ReadImage(filePaths[i]); sendM = new byte[image.Length + len + 4]; System.Buffer.BlockCopy(image, 0, sendM, 0, image.Length); System.Buffer.BlockCopy(nameb, 0, sendM, image.Length, len); System.Buffer.BlockCopy(num, 0, sendM, image.Length + len, 4); sender.Send(sendM); } filePaths = Directory.GetFiles("C:\\cygwin64\\home\\user\\coba\\SISTER\\", "*.jpg"); for (i = 0; i < filePaths.Length; i++) { name = filePaths[i].Replace("C:\\cygwin64\\home\\user\\coba\\SISTER\\", ""); nameb = GetBytes(name); len = nameb.Length; num = BitConverter.GetBytes(len); image = ReadImage(filePaths[i]); sendM = new byte[image.Length + len + 4]; System.Buffer.BlockCopy(image, 0, sendM, 0, image.Length); System.Buffer.BlockCopy(nameb, 0, sendM, image.Length, len); System.Buffer.BlockCopy(num, 0, sendM, image.Length + len, 4); sender.Send(sendM); } //Image output = byteArrayToImage(image); //SaveFile(output); Console.WriteLine("Press Enter to quit"); Console.ReadLine(); } } } }
protected override PushSocket CreateProducerSocket(NetMQContext context) { return(context.CreatePushSocket()); }