public void MultipleLargeMessages() { var largeMessage = new byte[12000]; for (int i = 0; i < 12000; i++) { largeMessage[i] = (byte)(i % 256); } using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { var port = pub.BindRandomPort("tcp://127.0.0.1"); sub.Connect("tcp://127.0.0.1:" + port); sub.Subscribe(""); Thread.Sleep(1000); pub.SendFrame(""); sub.SkipFrame(); for (int i = 0; i < 100; i++) { pub.SendFrame(largeMessage); byte[] recvMesage = sub.ReceiveFrameBytes(); for (int j = 0; j < 12000; j++) { Assert.AreEqual(largeMessage[j], recvMesage[j]); } } } }
public void Test_Two_Subscribers() { NUnitUtils.PrintTestName(); var sw = Stopwatch.StartNew(); using (var pub = new PublisherSocket()) { using (var sub1 = new SubscriberSocket()) { using (var sub2 = new SubscriberSocket()) { var freePort = NUnitUtils.TcpPortFree(); pub.Bind("tcp://127.0.0.1:" + freePort); sub1.Connect("tcp://127.0.0.1:" + freePort); sub1.Subscribe("A"); sub2.Connect("tcp://127.0.0.1:" + freePort); sub2.Subscribe("B"); Thread.Sleep(500); var swInner = Stopwatch.StartNew(); { pub.SendFrame("A\n"); // Ping. { string topic; var pass1 = sub1.TryReceiveFrameString(TimeSpan.FromMilliseconds(250), out topic); if (pass1) { Console.Write(topic); } else { Assert.Fail(); } } pub.SendFrame("B\n"); // Ping. { string topic; var pass2 = sub2.TryReceiveFrameString(TimeSpan.FromMilliseconds(250), out topic); if (pass2) { Console.Write(topic); } else { Assert.Fail(); } } } Console.WriteLine("Connected in {0} ms.", swInner.ElapsedMilliseconds); } } } NUnitUtils.PrintElapsedTime(sw.Elapsed); }
public static void Main(string[] args) { const int MegaBit = 1024; const int MegaByte = 1024; using (var pub = new PublisherSocket()) using (var sub1 = new SubscriberSocket()) using (var sub2 = new SubscriberSocket()) { 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"); sub1.Options.ReceiveBuffer = MegaByte * 10; sub1.Bind("pgm://224.0.0.1:5555"); sub1.Subscribe(""); sub2.Bind("pgm://224.0.0.1:5555"); sub2.Options.ReceiveBuffer = MegaByte * 10; sub2.Subscribe(""); Console.WriteLine("Server sending 'Hi'"); pub.SendFrame("Hi", false); bool more; Console.WriteLine("sub1 received = '{0}'", sub1.ReceiveFrameString(out more)); Console.WriteLine("sub2 received = '{0}'", sub2.ReceiveFrameString(out more)); } }
private static void Main() { Console.Title = "NetMQ Weather Update Server"; bool stopRequested = false; // Wire up the CTRL+C handler Console.CancelKeyPress += (sender, e) => stopRequested = true; Console.WriteLine("Publishing weather updates..."); using (var publisher = new PublisherSocket()) { publisher.Bind("tcp://127.0.0.1:5556"); var rng = new Random(); while (!stopRequested) { int zipcode = rng.Next(0, 99999); int temperature = rng.Next(-80, 135); int relhumidity = rng.Next(0, 90); publisher.SendFrame($"{zipcode} {temperature} {relhumidity}"); } } }
static void Main(string[] args) { var weathers = new string[6] { "晴朗", "多云", "阴天", "霾", "雨", "雪" }; Console.WriteLine("发布多个地区天气预报:"); using (var publisher = new PublisherSocket()) { publisher.Bind("tcp://127.0.0.1:8888"); var rng = new Random(); while (_terminateEvent.WaitOne(1000) == false) { var zipcode = rng.Next(0, 10); var temperature = rng.Next(-50, 50); var weatherId = rng.Next(0, 5); var msg = $"{zipcode} {temperature} {weathers[weatherId]}"; publisher.SendFrame(msg); Console.WriteLine(msg); Thread.Sleep(1000); } } }
public void SetPgmSettings() { const int MegaBit = 1024; const int MegaByte = 1024; using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { 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"); sub.Options.ReceiveBuffer = MegaByte * 10; sub.Bind("pgm://224.0.0.1:5555"); sub.Subscribe(""); pub.SendFrame("Hi"); bool more; Assert.AreEqual("Hi", sub.ReceiveFrameString(out more)); Assert.IsFalse(more); 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.ReceiveBuffer); } }
public void PubSub() { ThreadPool.QueueUserWorkItem(state => { var server = new PublisherSocket(); server.Bind("tcp://*:5557"); while (!_stopLoops) { try { var dataFacadeEvent = new DataFacadeEvent { State = new List <User> { new User { Id = 666 } } }; using (var responseStream = new MemoryStream()) { Serializer.Serialize(responseStream, dataFacadeEvent); server.SendFrame(responseStream.ToArray()); } Thread.Sleep(5000); } catch (Exception e) { Console.WriteLine(e); } } }); }
public void UseInterface() { #if NETCOREAPP1_0 var hostEntry = Dns.GetHostEntryAsync(Dns.GetHostName()).Result; #else var hostEntry = Dns.GetHostEntry(Dns.GetHostName()); #endif string ip = hostEntry.AddressList .Where(addr => addr.AddressFamily == AddressFamily.InterNetwork) .Select(addr => addr.ToString()) .FirstOrDefault(); using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { pub.Connect($"pgm://{ip};224.0.0.1:5555"); sub.Bind($"pgm://{ip};224.0.0.1:5555"); sub.Subscribe(""); pub.SendFrame("Hi"); bool more; Assert.AreEqual("Hi", sub.ReceiveFrameString(out more)); Assert.IsFalse(more); } }
public void TwoPublishers() { using (var pub = new PublisherSocket()) using (var pub2 = new PublisherSocket()) using (var sub = new SubscriberSocket()) { pub.Connect("pgm://224.0.0.1:5555"); pub2.Connect("pgm://224.0.0.1:5555"); sub.Bind("pgm://224.0.0.1:5555"); sub.Subscribe(""); pub.SendFrame("Hi"); bool more; Assert.AreEqual("Hi", sub.ReceiveFrameString(out more)); Assert.IsFalse(more); pub2.SendFrame("Hi2"); Assert.AreEqual("Hi2", sub.ReceiveFrameString(out more)); Assert.IsFalse(more); } }
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; } } }
public bool SendMessage() { var netMqTimer = new NetMQTimer(100); var timer = new Timer(180000); timer.Start(); timer.Elapsed += (sender, args) => { this.Cancel = true; timer.Stop(); }; using (var publisher = new PublisherSocket()) { publisher.Bind("tcp://*:3245"); Thread.Sleep(3000); var rng = new Random(); while (!Cancel) { var zipcode = 10001;//rng.Next(0, 99999); var temperature = rng.Next(-80, 135); var humidity = rng.Next(0, 90); publisher.SendFrame($"{zipcode} {temperature} {humidity}"); } } return(true); }
public void LargeMessage() { using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { pub.Connect("pgm://224.0.0.1:5555"); sub.Bind("pgm://224.0.0.1:5555"); sub.Subscribe(""); var data = new byte[3200]; // this should be at least 3 packets for (Int16 i = 0; i < 1600; i++) { Array.Copy(BitConverter.GetBytes(i), 0, data, i * 2, 2); } pub.SendFrame(data); byte[] message = sub.ReceiveFrameBytes(); Assert.AreEqual(3200, message.Length); for (Int16 i = 0; i < 1600; i++) { Assert.AreEqual(i, BitConverter.ToInt16(message, i * 2)); } } }
private static void Main() { Console.Title = "NetMQ Weather Update Server"; bool stopRequested = false; // Wire up the CTRL+C handler Console.CancelKeyPress += (sender, e) => stopRequested = true; Console.WriteLine("Publishing weather updates..."); using (var publisher = new PublisherSocket()) { publisher.Bind("tcp://127.0.0.1:5556"); var rng = new Random(); while (!stopRequested) { int zipcode = rng.Next(0, 99999); int temperature = rng.Next(-80, 135); int relhumidity = rng.Next(0, 90); publisher.SendFrame(string.Format("{0} {1} {2}", zipcode, temperature, relhumidity)); } } }
public void PubSub_Should_NotCrash_IfNo_Thread_Sleep() { using (var pub = new PublisherSocket()) { using (var sub = new SubscriberSocket()) { int freePort = TcpPortFree(); pub.Bind("tcp://127.0.0.1:" + freePort); sub.Connect("tcp://127.0.0.1:" + freePort); sub.Subscribe("*"); Stopwatch sw = Stopwatch.StartNew(); { for (int i = 0; i < 50; i++) { pub.SendFrame("*"); // Ping. Console.Write("*"); string topic; var gotTopic = sub.TryReceiveFrameString(TimeSpan.FromMilliseconds(100), out topic); string ping; var gotPing = sub.TryReceiveFrameString(TimeSpan.FromMilliseconds(100), out ping); if (gotTopic == true) { Console.Write("\n"); break; } } } Console.WriteLine("Connected in {0} ms.", sw.ElapsedMilliseconds); } } }
public void LargerBufferLength() { var largerBuffer = new byte[256]; { largerBuffer[124] = 0xD; largerBuffer[125] = 0xE; largerBuffer[126] = 0xE; largerBuffer[127] = 0xD; } using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { var port = pub.BindRandomPort("tcp://127.0.0.1"); sub.Connect("tcp://127.0.0.1:" + port); sub.Subscribe(""); Thread.Sleep(100); pub.SendFrame(largerBuffer, 128); byte[] recvMesage = sub.ReceiveFrameBytes(); Assert.AreEqual(128, recvMesage.Length); Assert.AreEqual(0xD, recvMesage[124]); Assert.AreEqual(0xE, recvMesage[125]); Assert.AreEqual(0xE, recvMesage[126]); Assert.AreEqual(0xD, recvMesage[127]); Assert.AreNotEqual(largerBuffer.Length, recvMesage.Length); } }
protected override void Run() { AsyncIO.ForceDotNet.Force(); // this line is needed to prevent unity freeze after one use, not sure why yet using (SUB = new SubscriberSocket()) using (PUB = new PublisherSocket()) using (REQ = new RequestSocket()) { SUB.Connect("tcp://localhost:5555"); SUB.Subscribe(""); PUB.Connect("tcp://localhost:5556"); REQ.Connect("tcp://localhost:5557"); Debug.Log("Connected: Receiving Messages"); while (Running) { /*Receive continuos Slicer data*/ string msg = SUB.ReceiveFrameString(); /*Send continuos Unity data*/ var bytes = new byte[dataPackage.t.Length * 4]; System.Buffer.BlockCopy(dataPackage.t, 0, bytes, 0, bytes.Length); PUB.SendFrame(bytes); /*Request volume data once*/ if (reqestData) { REQ.SendFrame("volume"); string msg2 = REQ.ReceiveFrameString(); Debug.Log(msg2); byte[] file = System.IO.File.ReadAllBytes(msg2); Debug.Log(file.Length); int d1 = System.BitConverter.ToInt32(file, 0); int d2 = System.BitConverter.ToInt32(file, 4); int d3 = System.BitConverter.ToInt32(file, 8); float[] volume = new float[d1 * d2 * d3]; System.Buffer.BlockCopy(file, 12, volume, 0, volume.Length * sizeof(float)); string s = d1 + " " + d2 + " " + d3 + " : "; //for (int i = 0; i < volume.Length; ++i) s += volume[i] + " "; Debug.Log(s); reqestData = false; } /*60fps*/ System.Threading.Thread.Sleep(16); } SUB.Close(); PUB.Close(); REQ.Close(); } NetMQConfig.Cleanup(); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using var publisher = new PublisherSocket($">tcp://127.0.0.1:5555"); await Task.Delay(1000); _logger.LogInformation("Introducing the ball"); publisher.SendMoreFrame("ping"); publisher.SendMoreFrameEmpty(); publisher.SendFrame(Encoding.ASCII.GetBytes("The ball")); }
public void Sending1000Messages() { // creating two different context and sending 1000 messages int count = 0; var subReady = new ManualResetEvent(false); Task subTask = Task.Factory.StartNew(() => { using (var sub = new SubscriberSocket()) { sub.Bind("pgm://224.0.0.1:5555"); sub.Subscribe(""); subReady.Set(); while (count < 1000) { bool more; Assert.AreEqual(count, BitConverter.ToInt32(sub.ReceiveFrameBytes(out more), 0)); Assert.IsFalse(more); count++; } } }); subReady.WaitOne(); Task pubTask = Task.Factory.StartNew(() => { using (var pub = new PublisherSocket()) { pub.Connect("pgm://224.0.0.1:5555"); for (int i = 0; i < 1000; i++) { pub.SendFrame(BitConverter.GetBytes(i)); } // if we close the socket before the subscriber receives all messages subscriber // might miss messages, lets wait another second Thread.Sleep(1000); } }); pubTask.Wait(); subTask.Wait(); Thread.MemoryBarrier(); Assert.AreEqual(1000, count); }
static void Main(string[] args) { using (var publisher = new PublisherSocket()) { publisher.Bind("tcp://*:5555"); var random = new Random(); while (true) { publisher.SendFrame($"{random.Next(0, 1000)}"); } } }
public bool Send <T, C>(Message <T> request, C content, string msgType) { var ioPubMessage = new Message <C> { Identities = request.Identities, Delimiter = request.Delimiter, ParentHeader = request.Header, Header = new Header() { UserName = request.Header.UserName, Session = request.Header.Session, Date = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"), MessageId = Guid.NewGuid().ToString(), MessageType = msgType, Version = request.Header.Version }, Metadata = request.Metadata, Content = content }; var encoder = new UTF8Encoding(); List <string> messages = new List <string>(); var signature = Sign <C>(key, ioPubMessage, messages, iopub); // send foreach (var id in request.Identities) { iopub.TrySendFrame(encoder.GetBytes(id), true); } iopub.SendFrame(ioPubMessage.Delimiter, true); iopub.SendFrame(signature, true); for (int i = 0; i < messages.Count; i++) { iopub.SendFrame(messages[i], i < messages.Count - 1); } return(true); }
private void WorkFunction(object state) { string data = Guid.NewGuid().ToString(); Sock.SendFrame(data); int result = Interlocked.Increment(ref SentCounter); if (result % 200 == 0) { string msg = string.Format("{0} msg sent\r\n", result); UpdateTextBox(textBox1, msg); } }
public void Publish(MessageWrapper message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } byte[] rawBytes = Serializer.Serialize(message); lock (_publishSocketLocker) { _publishSocket.SendFrame(rawBytes); } }
public void BindBothSockets() { using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { pub.Bind("pgm://224.0.0.1:5555"); sub.Bind("pgm://224.0.0.1:5555"); sub.Subscribe(""); pub.SendFrame("Hi"); Assert.AreEqual("Hi", sub.ReceiveFrameString(out bool more)); Assert.IsFalse(more); } }
public void NotSubscribed() { using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { var port = pub.BindRandomPort("tcp://127.0.0.1"); sub.Connect("tcp://127.0.0.1:" + port); // let the subscriber connect to the publisher before sending a message Thread.Sleep(500); pub.SendFrame("Hello"); Assert.IsFalse(sub.TrySkipFrame()); } }
private void PublishEntry() { using (PublisherSocket publisher = new PublisherSocket()) { string endpoint = "tcp://*:" + ModPub.port; try { publisher.Bind(endpoint); } catch (Exception err) { Logging.logger.Error(ModName + " bind socket failed " + endpoint + " " + err.Message); throw (err); } PubRM.pubsock = publisher; string d = string.Empty; PubRM.Working = true; while (PubRM.Running) { d = string.Empty; //string received = serverSocket.ReceiveFrameString(); try { d = Entry4GetPubData(); } catch (Exception err) { Logging.logger.Error(err.Message); DelayTime(); continue; } if (d != null) { publisher.SendFrame(d); } DelayTime(); } PubRM.Working = false; publisher.Close(); } }
public void ReceiveMessageWithTimeout() { { var pubSync = new AutoResetEvent(false); var payload = new byte[300]; const int waitTime = 500; var t1 = new Task(() => { using (var pubSocket = new PublisherSocket()) { pubSocket.Bind("tcp://127.0.0.1:12345"); pubSync.WaitOne(); Thread.Sleep(waitTime); pubSocket.SendFrame(payload); pubSync.WaitOne(); } }, TaskCreationOptions.LongRunning); var t2 = new Task(() => { using (var subSocket = new SubscriberSocket()) { subSocket.Connect("tcp://127.0.0.1:12345"); subSocket.Subscribe(""); Thread.Sleep(100); pubSync.Set(); NetMQMessage msg = null; Assert.IsFalse(subSocket.TryReceiveMultipartMessage(TimeSpan.FromMilliseconds(100), ref msg)); Assert.IsTrue(subSocket.TryReceiveMultipartMessage(TimeSpan.FromMilliseconds(waitTime), ref msg)); Assert.NotNull(msg); Assert.AreEqual(1, msg.FrameCount); Assert.AreEqual(300, msg.First.MessageSize); pubSync.Set(); } }, TaskCreationOptions.LongRunning); t1.Start(); t2.Start(); Task.WaitAll(t1, t2); } }
void StartServer() { Debug.Log("Start Server!"); using (PullSocket pullSocket = new PullSocket()) using (PublisherSocket publisherSocket = new PublisherSocket()) { pullSocket.Bind("tcp://*:20002"); publisherSocket.Bind("tcp://*:20001"); while (true) { string str = pullSocket.ReceiveFrameString(); Debug.Log("[Server] Get! :: " + str); publisherSocket.SendFrame("Hello Client!"); Debug.Log("[Server] Send Hello Client!"); } } }
static void Main(string[] args) { string endpoint = "tcp://*:5556"; using (var socket = new PublisherSocket()) { socket.Bind(endpoint); for (var i = 0; i < 500; i++) { var msg = "OPCE TopicA msg-" + i; Console.WriteLine("Sending message : {0}", msg); socket.SendFrame(msg); Thread.Sleep(10000); } } }
public override void Publisher() { AsyncIO.ForceDotNet.Force(); sender = new PublisherSocket(); sender.Connect("tcp://" + IP + ":" + Port); //Debug.Log("Connect ObjectSender to: " + "tcp://" + IP + ":" + Port); while (IsRunning) { Thread.Sleep(1); if (sendMessageQueue.Count > 0) { //Debug.Log("Send: " + sendMessageQueue[0]); sender.SendFrame(sendMessageQueue[0], false); // true not wait sendMessageQueue.RemoveAt(0); } } // disconnectClose(); }
public void LargeMessage() { using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { var port = pub.BindRandomPort("tcp://127.0.0.1"); sub.Connect("tcp://127.0.0.1:" + port); sub.Subscribe(""); Thread.Sleep(100); var msg = new byte[300]; pub.SendFrame(msg); byte[] msg2 = sub.ReceiveFrameBytes(); Assert.AreEqual(300, msg2.Length); } }
public void SimplePubSub() { using (var pub = new PublisherSocket()) using (var sub = new SubscriberSocket()) { var port = pub.BindRandomPort("tcp://127.0.0.1"); sub.Connect("tcp://127.0.0.1:" + port); sub.Subscribe(""); // let the subscriber connect to the publisher before sending a message Thread.Sleep(500); // Send the topic only pub.SendFrame("A"); CollectionAssert.AreEqual( new[] { "A" }, sub.ReceiveMultipartStrings()); } }