public void MultipleSubscribersOnDifferentTopics() { using (var pub = new PublisherSocket()) using (var sub1 = new SubscriberSocket()) using (var sub2 = new SubscriberSocket()) { var port = pub.BindRandomPort("tcp://127.0.0.1"); sub1.Connect("tcp://127.0.0.1:" + port); sub2.Connect("tcp://127.0.0.1:" + port); sub1.Subscribe("1"); sub1.Subscribe("1&2"); sub2.Subscribe("2"); sub2.Subscribe("1&2"); Thread.Sleep(500); pub.SendMoreFrame("1").SendFrame("A"); CollectionAssert.AreEqual(new[] { "1", "A" }, sub1.ReceiveMultipartStrings()); Assert.IsFalse(sub2.TrySkipFrame()); pub.SendMoreFrame("2").SendFrame("B"); Assert.IsFalse(sub1.TrySkipFrame()); CollectionAssert.AreEqual(new[] { "2", "B" }, sub2.ReceiveMultipartStrings()); pub.SendMoreFrame("1&2").SendFrame("C"); CollectionAssert.AreEqual(new[] { "1&2", "C" }, sub1.ReceiveMultipartStrings()); CollectionAssert.AreEqual(new[] { "1&2", "C" }, sub2.ReceiveMultipartStrings()); } }
public void OnNext(T message) { try { InitializePublisherOnFirstUse(); // Publish message using ZeroMQ as the transport mechanism. m_publisherSocket.SendMoreFrame(QueueName) .SendMoreFrame("N") // "N", "E" or "C" for "OnNext", "OnError" or "OnCompleted". .SendFrame(message.SerializeProtoBuf <T>()); // Comment in the remaining code for the standard pub/sub pattern. //if (this.HasObservers == false) //{ //throw new QxNoSubscribers("Error E23444. As there are no subscribers to this publisher, this event will be lost."); //} //lock (_subscribersLock) //{ //this._subscribers.ForEach(msg => msg.OnNext(message)); //} } catch (Exception ex) { var col = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Exception: {0}", ex.Message); Console.ForegroundColor = col; this.OnError(ex); throw; } }
private static void PublisherSocket() { Random rand = new Random(50); using var pubSocket = new PublisherSocket(); Console.WriteLine("Publisher socket binding..."); pubSocket.Options.SendHighWatermark = 1000; pubSocket.Bind("tcp://*:12345"); for (var i = 0; i < 100; i++) { var randomizedTopic = rand.NextDouble(); if (randomizedTopic > 0.5) { var msg = "TopicA msg-" + i; Console.WriteLine("Sending message : {0}", msg); pubSocket.SendMoreFrame("TopicA").SendFrame(msg); } else { var msg = "TopicB msg-" + i; Console.WriteLine("Sending message : {0}", msg); pubSocket.SendMoreFrame("TopicB").SendFrame(msg); } Thread.Sleep(500); } }
static void XPub() { var a2 = $"{address}:55507"; using (var pubSocket = new PublisherSocket(a2)) { Console.WriteLine("Publisher socket connecting..."); pubSocket.Options.SendHighWatermark = 1000; var rand = new Random(50); while (true) { Thread.Sleep(1000); var randomizedTopic = rand.NextDouble(); if (randomizedTopic > 0.5) { var msg = "TopicA msg-" + randomizedTopic; Console.WriteLine("Sending message : {0}", msg); pubSocket.SendMoreFrame("TopicA").SendFrame(msg); } else { var msg = "TopicB msg-" + randomizedTopic; Console.WriteLine("Sending message : {0}", msg); pubSocket.SendMoreFrame("TopicB").SendFrame(msg); } } } }
public void Unsubscribe() { using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { int port = pub.BindRandomPort("tcp://127.0.0.1"); sub.Connect("tcp://127.0.0.1:" + port); sub.Subscribe("A"); // let the subscriber connect to the publisher before sending a message Thread.Sleep(500); pub.SendMoreFrame("A").SendFrame("Hello"); CollectionAssert.AreEqual(new[] { "A", "Hello" }, sub.ReceiveMultipartStrings()); sub.Unsubscribe("A"); Thread.Sleep(500); pub.SendMoreFrame("A").SendFrame("Hello again"); Assert.IsFalse(sub.TrySkipFrame()); } }
private static void XPublisherSocket() { using var pubSocket = new PublisherSocket(">tcp://127.0.0.1:5678"); Console.WriteLine("Publisher socket connecting..."); pubSocket.Options.SendHighWatermark = 1000; var rand = new Random(50); while (true) { var randomizedTopic = rand.NextDouble(); if (randomizedTopic > 0.5) { var msg = randomizedTopic.ToString(); Console.WriteLine("Sending message : {0}", msg); pubSocket.SendMoreFrame($"{TopicEvnet.YcYxSetChangeEvent}/1").SendFrame(msg); } else { var msg = "TopicB msg-" + randomizedTopic; Console.WriteLine("Sending message : {0}", msg); pubSocket.SendMoreFrame("TopicB").SendFrame(msg); } Thread.Sleep(500); } }
/// <summary> /// Publishes the specified message. /// </summary> /// <param name="message">The message to publish.</param> public void Publish(object message) { string topic = _topicBuilder.GetMessageTag(_selfIdentity.Context, message.GetType()); // Use message type as a topic string serializedMessage = WrapMessage(message).ToString(); _socket.SendMoreFrame(Encode(topic)).SendFrame(Encode(serializedMessage)); }
public void Publish(string topicName, string data) { lock (_lockObj) { strTopics.Add(topicName); _publisher.SendMoreFrame(topicName).SendFrame(data); } }
void publicData() // wysyłanie danych jako publisher z wybraniem CPU, RAM itd. { using (var pubSocket = new PublisherSocket()) { pubSocket.Bind("tcp://*:12345"); while (true) { if (pubCPU.Checked) { string messageTopic = "CPU"; float fCPU = perfCPU.NextValue(); string messageContent = fCPU.ToString(); pubSocket.SendMoreFrame(messageTopic).SendFrame(messageContent); MethodInvoker methodInvoker = () => sendLogs(messageTopic, messageContent); Invoke(methodInvoker); } if (pubRAM.Checked) { string messageTopic = "RAM"; float fRAM = perfRAM.NextValue(); string messageContent = fRAM.ToString(); pubSocket.SendMoreFrame(messageTopic).SendFrame(messageContent); MethodInvoker methodInvoker = () => sendLogs(messageTopic, messageContent); Invoke(methodInvoker); } if (pubDisk.Checked) { string messageTopic = "DYSK"; float fDisk = perfDisk.NextValue(); string messageContent = fDisk.ToString(); pubSocket.SendMoreFrame(messageTopic).SendFrame(messageContent); MethodInvoker methodInvoker = () => sendLogs(messageTopic, messageContent); Invoke(methodInvoker); } try { Thread.Sleep(Int32.Parse(timeText.Text) * 1000); } catch (FormatException fe) { MessageBox.Show(fe.Message); string timeToSent = "10"; MethodInvoker mi = new MethodInvoker(() => timeText.Text = timeToSent); Invoke(mi); } } } }
public async Task ShouldHandleStateOfTheWorldRequest() { using (var publisher = new PublisherSocket()) { publisher.Connect(ToPublishersEndpoint); var command1 = new ChangeCcyPairState("EUR/USD", "TEST2", CcyPairState.Passive); var command2 = new ChangeCcyPairState("EUR/USD", "TEST2", CcyPairState.Active); var message1 = _eventSerializer.ToProducerMessage(command1); var message2 = _eventSerializer.ToProducerMessage(command2); await Task.Delay(200); publisher.SendMoreFrame(message1.Subject) .SendFrame(_eventSerializer.Serializer.Serialize(message1)); await Task.Delay(200); publisher.SendMoreFrame(message2.Subject) .SendFrame(_eventSerializer.Serializer.Serialize(message2)); await Task.Delay(200); var cacheItems = await _eventCache.GetAllStreams(); Assert.AreEqual(2, cacheItems.Count()); using (var dealer = new DealerSocket()) { var request = new StateRequest() { Subject = "EUR/USD" }; var requestBytes = _eventSerializer.Serializer.Serialize(request); dealer.Connect(StateOfTheWorldEndpoint); dealer.SendFrame(requestBytes); var hasResponse = dealer.TryReceiveFrameBytes(TimeSpan.FromMilliseconds(1000), out var responseBytes); var response = _eventSerializer.Serializer.Deserialize <StateReply>(responseBytes); Assert.AreEqual(2, response.Events.Count()); } } }
private static void Pull_ReceiveReady1(object sender, NetMQSocketEventArgs e) { var fileByte = e.Socket.ReceiveFrameBytes(); var md5Str = Encoding.UTF8.GetString(fileByte.Take(128).ToArray()); var time = Encoding.UTF8.GetString(fileByte.Skip(md5Str.Length).Take(17).ToArray()); DateTime sendTime = DateTime.ParseExact(time, "yyyyMMddHHmmssfff", null); int takeSize = md5Str.Length + time.Length; var bodyBytes = fileByte.Skip(takeSize).TakeLast(fileByte.Length - takeSize).ToArray(); DateTime reciveDateTime = System.DateTime.Now; string md5 = MD5(bodyBytes); if (!string.Equals(md5Str, md5)) { Console.Out.WriteLine($"上传文件不合法, {System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")}"); } else { Console.Out.WriteLine($"接收文件成功,文件大小为{bodyBytes.Length}, {reciveDateTime.ToString("yyyy-MM-dd HH:mm:ss fff")},发送时间为{sendTime.ToString("yyyy-MM-dd HH:mm:ss fff")},耗时:{(reciveDateTime - sendTime).TotalMilliseconds}"); } string addr = @$ "{e.Socket.Options.LastEndpoint}"; publisherSocket.SendMoreFrame(addr).SendFrame("test"); }
public void Run() { Task.Run(async() => { using (var pubSocket = new PublisherSocket()) { Console.WriteLine("Publisher socket binding..."); pubSocket.Options.SendHighWatermark = 1000; pubSocket.Bind("tcp://localhost:12345"); while (true) { var stories = await FetchBestStories(); if (stories != null) { Console.WriteLine($"Sending {stories.Count} stories"); pubSocket.SendMoreFrame("Stories").SendFrame(JsonConvert.SerializeObject(stories)); } await Task.Delay(IntervalSecs * 1000); } } }); }
private void Produce() { var eventSerializer = new EventSerializer(); _publisherSocket = new PublisherSocket(); _publisherSocket.Options.SendHighWatermark = 1000; _publisherSocket.Bind(_producerConfiguration.Endpoint); while (!_cancel.IsCancellationRequested) { var next = Next(); var topic = eventSerializer.Serialize(next); var message = new TransportMessage() { MessageType = next.GetType(), MessageId = Guid.NewGuid(), Message = Encoding.UTF32.GetBytes(JsonConvert.SerializeObject(next, _settings)), }; var msg = Encoding.UTF32.GetBytes(JsonConvert.SerializeObject(message, _settings)); _publisherSocket.SendMoreFrame(topic).SendFrame(msg); Task.Delay(_rand.Next(250, 500)).Wait(); } }
public static void Publish() { using (var pub = new PublisherSocket()) { bool usePlain = true; if (usePlain) { pub.Options.PlainUsername = "******"; pub.Options.PlainPassword = "******"; pub.Options.PlainServer = true; } pub.Bind("tcp://192.168.0.193:6021"); int i = 0; while (true) { Thread.Sleep(500); pub.SendMoreFrame("A").SendFrame("Hello - " + i++); Console.WriteLine("SENDING MESSAGE on port 6021"); } Console.WriteLine(); Console.Write("Press any key to exit..."); Console.ReadKey(); } }
public void Emit(LogEvent logEvent) { var message = logEvent.RenderMessage(fmtProvider); var level = logEvent.Level.ToString(); publisherSocket.SendMoreFrame(level).SendFrame(message); }
/// <summary> /// 发送数据 /// </summary> /// <param name="data"></param> public void Send(string data) { if (!string.IsNullOrEmpty(data)) { publisher.SendMoreFrame("A").SendFrame(data); } }
static void Main(string[] args) { Random rand = new Random(50); using (var pubSocket = new PublisherSocket()) { Console.WriteLine("Publisher socket binding..."); pubSocket.Options.SendHighWatermark = 100; pubSocket.Bind("tcp://localhost:12345"); Thread.Sleep(200); pubSocket.SendMoreFrame("").SendFrame("1231231231313123131231"); //for (var i = 0; i < 300; i++) //{ // var randomizedTopic = rand.NextDouble(); // if (randomizedTopic > 0.5) // { // var msg = "TopicA msg-" + i; // Console.WriteLine("Sending message : {0}", msg); // pubSocket.SendMoreFrame("TopicA").SendFrame(msg); // } // else // { // var msg = "TopicB msg-" + i; // Console.WriteLine("Sending message : {0}", msg); // pubSocket.SendMoreFrame("TopicB").SendFrame(msg); // } // Thread.Sleep(100); //} } }
private void HandleWork() { using (var stateUpdate = new SubscriberSocket()) { stateUpdate.SubscribeToAnyTopic(); stateUpdate.Bind(_configuration.ToPublisherEndpoint); using (var stateUpdatePublish = new PublisherSocket()) { stateUpdatePublish.Bind(_configuration.ToSubscribersEndpoint); stateUpdate.ReceiveReady += async(s, e) => { var message = e.Socket.ReceiveMultipartMessage(); var subject = message[0].ConvertToString(); var payload = message[1]; var eventId = await _cache.AppendToStream(subject, payload.Buffer); stateUpdatePublish.SendMoreFrame(message[0].Buffer) .SendMoreFrame(_serializer.Serialize(eventId)) .SendFrame(payload.Buffer); }; using (_poller = new NetMQPoller { stateUpdate, stateUpdatePublish }) { _poller.Run(); } } } }
public void MultiplePublishersAndSubscribersOnSameTopic() { using (var pub1 = new PublisherSocket()) using (var pub2 = new PublisherSocket()) using (var sub1 = new SubscriberSocket()) using (var sub2 = new SubscriberSocket()) { int port1 = pub1.BindRandomPort("tcp://127.0.0.1"); int port2 = pub2.BindRandomPort("tcp://127.0.0.1"); sub1.Connect("tcp://127.0.0.1:" + port1); sub1.Connect("tcp://127.0.0.1:" + port2); sub2.Connect("tcp://127.0.0.1:" + port1); sub2.Connect("tcp://127.0.0.1:" + port2); // should subscribe to both sub1.Subscribe("A"); sub2.Subscribe("A"); Thread.Sleep(500); // Send from pub 1 pub1.SendMoreFrame("A").SendFrame("Hello from the first publisher"); CollectionAssert.AreEqual(new[] { "A", "Hello from the first publisher" }, sub1.ReceiveMultipartStrings()); CollectionAssert.AreEqual(new[] { "A", "Hello from the first publisher" }, sub2.ReceiveMultipartStrings()); // Send from pub 2 pub2.SendMoreFrame("A").SendFrame("Hello from the second publisher"); CollectionAssert.AreEqual(new[] { "A", "Hello from the second publisher" }, sub1.ReceiveMultipartStrings()); CollectionAssert.AreEqual(new[] { "A", "Hello from the second publisher" }, sub2.ReceiveMultipartStrings()); } }
static void Main(string[] args) { using (var pubSocket = new PublisherSocket()) { using (var subSocket = new SubscriberSocket()) { pubSocket.Bind("tcp://127.0.0.1:55555"); var msg = new BlockedOrderCreated(); // pubSocket.SendMoreFrame("BlockedOrderTopic").SendFrame(msg.content); Thread.Sleep(500); subSocket.Connect("tcp://127.0.0.1:55555"); Thread.Sleep(500); subSocket.Subscribe("BlockedOrderTopic"); pubSocket.SendMoreFrame("BlockedOrderTopic").SendFrame(msg.content); while (true) { Thread.Sleep(500); var messageReceived = subSocket.ReceiveFrameString(); Thread.Sleep(500); Debug.WriteLine(messageReceived); } } } }
private async Task RunAsync(CancellationToken stoppingToken) { using var subscriber = new SubscriberSocket($">tcp://127.0.0.1:4444"); subscriber.Subscribe("ping"); using var publisher = new PublisherSocket($">tcp://127.0.0.1:5555"); _logger.LogInformation("Pong service ready"); while (!stoppingToken.IsCancellationRequested) { try { var msg = await subscriber.ReceiveMultipartMessageAsync(cancellationToken : stoppingToken); if (stoppingToken.IsCancellationRequested) { break; } _logger.LogInformation("Ping received"); await Task.Delay(100); publisher.SendMoreFrame("pong"); publisher.SendMoreFrameEmpty(); publisher.SendFrame(msg[2].Buffer); } catch (Exception e) { _logger.LogError(e, "ERROR in PingService"); break; } } }
/// <summary> /// This Function will Publish the data you gave in. /// </summary> /// <param name="data">a bye array where your data is stored</param> public void Publish(byte[] data) { if (Publisher != null) { Publisher.SendMoreFrame(Topic).SendFrame(data); } }
public void CloseApp() { if (pubSocket != null) { pubSocket.SendMoreFrame("CloseApp").SendFrame(""); } }
public void Execute() { using (var jobServerValidationBackend = new PublisherSocket(PUBLISHER)) using (var jobServerFrontend = new SubscriberSocket(JOB_SERVER_FRONTEND_ENDPOINT)) { jobServerFrontend.Subscribe("init"); Console.WriteLine("Job server ONNNNNNNNNNNNNNNNNN"); Console.WriteLine($"Publisher running on: {PUBLISHER}"); Console.WriteLine($"Listening to: {JOB_SERVER_FRONTEND_ENDPOINT}"); while (true) { try { var topic = jobServerFrontend.ReceiveFrameString(); var event_job_message = jobServerFrontend.ReceiveFrameString(); var envelope = Newtonsoft.Json.JsonConvert.DeserializeObject <Envelope>(event_job_message); Console.WriteLine($"Receive: {envelope.Identity}"); jobServerValidationBackend.SendMoreFrame("validation").SendFrame(event_job_message); } catch (Exception ex) //Drop message { Console.WriteLine("Erro na validação do dado: " + ex.Message); } } } }
static void Main(string[] args) { Random rand = new Random(50); using (var pubSocket = new PublisherSocket()) { Console.WriteLine("Publisher socket binding..."); pubSocket.Options.SendHighWatermark = 100; pubSocket.Bind("tcp://localhost:12345"); Thread.Sleep(200); pubSocket.SendMoreFrame("").SendFrame("1231231231313123131231"); //for (var i = 0; i < 300; i++) //{ // var randomizedTopic = rand.NextDouble(); // if (randomizedTopic > 0.5) // { // var msg = "TopicA msg-" + i; // Console.WriteLine("Sending message : {0}", msg); // pubSocket.SendMoreFrame("TopicA").SendFrame(msg); // } // else // { // var msg = "TopicB msg-" + i; // Console.WriteLine("Sending message : {0}", msg); // pubSocket.SendMoreFrame("TopicB").SendFrame(msg); // } // Thread.Sleep(100); //} } }
public async Task ShouldSubscribeToSpecificSubject() { using (var publisherSocket = new PublisherSocket()) { publisherSocket.Bind(ToSubscribersEndpoint); var createEvent = new Func <string, string, Task>(async(streamId, market) => { var @event = new ChangeCcyPairPrice(streamId, market, 0.0, 0.0, 0.0, 0.0); var message = _eventSerializer.ToProducerMessage(@event); var eventId = new EventId(streamId, 0, string.IsNullOrEmpty(market) ? streamId : $"{streamId}.{market}", DateTime.Now.Ticks); publisherSocket.SendMoreFrame(message.Subject) .SendMoreFrame(_serializer.Serialize(eventId)) .SendFrame(_serializer.Serialize(message)); await Task.Delay(500); }); var subscribedToStreamId = "EUR/USD"; var subscribedToMarket = "Harmony"; var NOTsubscribedToStreamId = "EUR/GBP"; var NOTsubscribedToMarket = "FxConnect"; var cacheConfiguration = new DynamicCacheConfiguration(ToSubscribersEndpoint, StateOfTheWorldEndpoint, HeartbeatEndpoint) { Subject = $"{subscribedToStreamId}.{subscribedToMarket}", HeartbeatDelay = TimeSpan.FromSeconds(1), HeartbeatTimeout = TimeSpan.FromSeconds(1), }; var cache = new DynamicCache <string, CurrencyPair>(cacheConfiguration, LoggerForTests <DynamicCache <string, CurrencyPair> > .Default(), _eventSerializer); await cache.Run(); await Task.Delay(1000); await createEvent(NOTsubscribedToStreamId, NOTsubscribedToMarket); Assert.AreEqual(0, cache.Items.SelectMany(ccy => ccy.AppliedEvents).Count()); await createEvent(NOTsubscribedToStreamId, subscribedToMarket); Assert.AreEqual(0, cache.Items.SelectMany(ccy => ccy.AppliedEvents).Count()); await createEvent(subscribedToStreamId, NOTsubscribedToMarket); Assert.AreEqual(0, cache.Items.SelectMany(ccy => ccy.AppliedEvents).Count()); await createEvent(subscribedToStreamId, subscribedToMarket); Assert.AreEqual(1, cache.Items.SelectMany(ccy => ccy.AppliedEvents).Count()); await createEvent(subscribedToStreamId, string.Empty); Assert.AreEqual(1, cache.Items.SelectMany(ccy => ccy.AppliedEvents).Count()); } }
public void Emit(String msg) { if (Started) { Server.SendMoreFrame("update").SendFrame(msg); } }
public void Publish(string topic, string message) { //try //{ _pusSocket.SendMoreFrame(topic).SendFrame(message); //} //catch { } }
public void Publish(IEvent<TKey, TAggregate> @event) { if (_state.Value != ProducerState.Connected) throw new InvalidOperationException("publisher is not connected"); var message = _eventSerializer.ToProducerMessage(@event); _publisherSocket.SendMoreFrame(message.Subject) .SendFrame(_eventSerializer.Serializer.Serialize(message)); }
void publicData() { using (var pubSocket = new PublisherSocket()) { pubSocket.Bind("tcp://*:12345"); while (true) { if (publicDate.Checked) { string messageTopic = "date"; string messageContent = DateTime.Now.ToString("dddd, dd MMMM yyyy"); pubSocket.SendMoreFrame(messageTopic).SendFrame(messageContent); MethodInvoker methodInvoker = () => sendLogs(messageTopic, messageContent); Invoke(methodInvoker); } if (publicTime.Checked) { string messageTopic = "time"; string messageContent = DateTime.Now.ToString("HH:mm:ss"); pubSocket.SendMoreFrame(messageTopic).SendFrame(messageContent); MethodInvoker methodInvoker = () => sendLogs(messageTopic, messageContent); Invoke(methodInvoker); } if (publicText.Checked) { string messageTopic = "text"; string messageContent = textContent.Text; pubSocket.SendMoreFrame(messageTopic).SendFrame(messageContent); MethodInvoker methodInvoker = () => sendLogs(messageTopic, messageContent); Invoke(methodInvoker); } try { Thread.Sleep(Int32.Parse(timeText.Text) * 1000); } catch (FormatException fe) { MessageBox.Show(fe.Message); MethodInvoker mi = new MethodInvoker(() => timeText.Text = "10"); Invoke(mi); } } } }
public void PublishProgress(TextProgressInfo progressInfo) { TraceExtensions.WriteInfoLine($"PublishProgress: {progressInfo.Text}"); using (var socket = new PublisherSocket()) { socket.Options.SendHighWatermark = 1000; socket.Bind(StatusUri.OriginalString); socket.SendMoreFrame(Topic).SendFrame(progressInfo.Text); } }
public void InsertNetMQ(string didiStr) { using (var pubSocket = new PublisherSocket()) { pubSocket.Options.SendHighWatermark = 10000; pubSocket.Bind("tcp://localhost:12345"); Thread.Sleep(500); pubSocket.SendMoreFrame("").SendFrame(didiStr); } }