public void ErrorCodeTest() { using (var req = new RequestSocket()) using (var rep = new ResponseSocket()) using (var monitor = new NetMQMonitor(req, "inproc://rep.inproc", SocketEvents.ConnectDelayed)) { var eventArrived = false; monitor.ConnectDelayed += (s, a) => { eventArrived = true; }; monitor.Timeout = TimeSpan.FromMilliseconds(100); var monitorTask = Task.Factory.StartNew(monitor.Start); var port = rep.BindRandomPort("tcp://127.0.0.1"); req.Connect("tcp://127.0.0.1:" + port); req.SendFrame("a"); rep.SkipFrame(); rep.SendFrame("b"); req.SkipFrame(); Thread.Sleep(200); Assert.IsTrue(eventArrived); monitor.Stop(); Thread.Sleep(200); Assert.IsTrue(monitorTask.IsCompleted); } }
public void MonitorDisposeProperlyWhenDisposedAfterMonitoredTcpSocket() { // The bug: // Given we monitor a netmq tcp socket // Given we disposed of the monitored socket first // When we dispose of the monitor // Then our monitor is Faulted with a EndpointNotFoundException // And monitor can't be stopped or disposed using (var res = new ResponseSocket()) { NetMQMonitor monitor; using (var req = new RequestSocket()) { monitor = new NetMQMonitor(req, "inproc://#monitor", SocketEvents.All); Task.Factory.StartNew(monitor.Start); // Bug only occurs when monitoring a tcp socket var port = res.BindRandomPort("tcp://127.0.0.1"); req.Connect("tcp://127.0.0.1:" + port); req.SendFrame("question"); Assert.That(res.ReceiveFrameString(), Is.EqualTo("question")); res.SendFrame("response"); Assert.That(req.ReceiveFrameString(), Is.EqualTo("response")); } Thread.Sleep(100); // Monitor.Dispose should complete var completed = Task.Factory.StartNew(() => monitor.Dispose()).Wait(1000); Assert.That(completed, Is.True); } // NOTE If this test fails, it will hang because context.Dispose will block }
public void Start() { if (IsRunning) { return; } _publisher = new PublisherSocket(); int pPort = _publisher.BindRandomPort("tcp://*"); _responserSocket = new ResponseSocket(); int rPort = _responserSocket.BindRandomPort("tcp://*"); _beacon.SelfNode.Arguments = string.Format("-p {0} -r {1}", pPort, rPort); HockSocketEvents(true); _poller = new NetMQPoller { _publisher, _responserSocket }; _poller.RunAsync(); _beacon.Start(); }
public void ResponsePoll() { using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) using (var poller = new NetMQPoller { rep }) { int port = rep.BindRandomPort("tcp://127.0.0.1"); req.Connect("tcp://127.0.0.1:" + port); rep.ReceiveReady += (s, e) => { bool more; Assert.AreEqual("Hello", e.Socket.ReceiveFrameString(out more)); Assert.False(more); e.Socket.SendFrame("World"); }; poller.RunAsync(); req.SendFrame("Hello"); bool more2; Assert.AreEqual("World", req.ReceiveFrameString(out more2)); Assert.IsFalse(more2); poller.Stop(); } }
public void ResponsePoll() { using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) using (var poller = new Poller(rep) { PollTimeout = TestPollTimeoutMillis }) { int port = rep.BindRandomPort("tcp://127.0.0.1"); req.Connect("tcp://127.0.0.1:" + port); rep.ReceiveReady += (s, e) => { bool more; Assert.AreEqual("Hello", e.Socket.ReceiveFrameString(out more)); Assert.False(more); e.Socket.SendFrame("World"); }; poller.PollTillCancelledNonBlocking(); req.SendFrame("Hello"); bool more2; Assert.AreEqual("World", req.ReceiveFrameString(out more2)); Assert.IsFalse(more2); poller.CancelAndJoin(); } }
public void ReceiveBeforeSending() { using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) { var port = rep.BindRandomPort("tcp://localhost"); req.Connect("tcp://localhost:" + port); Assert.Throws <FiniteStateMachineException>(() => req.ReceiveFrameBytes()); } }
public void SendMessageInResponeBeforeReceiving() { using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) { var port = rep.BindRandomPort("tcp://localhost"); req.Connect("tcp://localhost:" + port); Assert.Throws <FiniteStateMachineException>(() => rep.SendFrame("1")); } }
public void TestRebindSamePort() { int port; using (var response = new ResponseSocket()) { port = response.BindRandomPort("tcp://127.0.0.1"); response.Unbind(); } using (var response = new ResponseSocket()) { response.Bind($"tcp://127.0.0.1:{port}"); response.Unbind(); } }
public void SendingTwoRequestsInaRow() { using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) { var port = rep.BindRandomPort("tcp://localhost"); req.Connect("tcp://localhost:" + port); req.SendFrame("Hi"); rep.SkipFrame(); Assert.Throws <FiniteStateMachineException>(() => req.SendFrame("Hi2")); } }
/// <summary> /// 三经典模式:请求响应 /// </summary> static void ReqRep() { using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) { var port = rep.BindRandomPort(address); req.Connect(address + ":" + port); req.SendFrame("Hi"); Console.WriteLine(rep.ReceiveMultipartStrings().FirstOrDefault()); rep.SendFrame("Hi2"); Console.WriteLine(req.ReceiveMultipartStrings().FirstOrDefault()); } }
public ServiceStarter() : base() { var free_sock = new ResponseSocket(); free_sock_numb = free_sock.BindRandomPort("tcp://*"); Console.WriteLine("free socket is {0}", free_sock_numb); free_sock.Close(); service_addres = String.Format("tcp://*****:*****@" C:\programming\TopLevelProgram\cnn_service\start.py --port {0}", free_sock_numb); this.StartInfo.WorkingDirectory = @"C:\programming\TopLevelProgram\cnn_service\"; this.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; this.StartInfo.UseShellExecute = false; this.StartInfo.RedirectStandardOutput = true; this.StartInfo.RedirectStandardError = true; string cnn_outputPath = @"./log/output_cnn.txt"; using (StreamWriter sw = new StreamWriter(cnn_outputPath, false, System.Text.Encoding.Default)) { sw.WriteLine(DateTime.Now); } this.OutputDataReceived += new DataReceivedEventHandler((s, e) => { if (!String.IsNullOrEmpty(e.Data)) { using (StreamWriter sw = new StreamWriter(cnn_outputPath, true, System.Text.Encoding.Default)) { sw.WriteLine(e.Data); } } }); string cnn_errorPath = @"./log/error_cnn.txt"; using (StreamWriter sw = new StreamWriter(cnn_errorPath, false, System.Text.Encoding.Default)) { sw.WriteLine(DateTime.Now); } this.ErrorDataReceived += new DataReceivedEventHandler((s, e) => { if (!String.IsNullOrEmpty(e.Data)) { using (StreamWriter sw = new StreamWriter(cnn_errorPath, true, System.Text.Encoding.Default)) { sw.WriteLine(e.Data); } } }); }
public void SendMultipartMessage() { using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) { var port = rep.BindRandomPort("tcp://localhost"); req.Connect("tcp://localhost:" + port); req.SendMoreFrame("Hello").SendFrame("World"); CollectionAssert.AreEqual(new[] { "Hello", "World" }, rep.ReceiveMultipartStrings()); rep.SendMoreFrame("Hello").SendFrame("Back"); CollectionAssert.AreEqual(new[] { "Hello", "Back" }, req.ReceiveMultipartStrings()); } }
public void SimpleReqRep(string address) { using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) { var port = rep.BindRandomPort(address); req.Connect(address + ":" + port); req.SendFrame("Hi"); CollectionAssert.AreEqual(new[] { "Hi" }, rep.ReceiveMultipartStrings()); rep.SendFrame("Hi2"); CollectionAssert.AreEqual(new[] { "Hi2" }, req.ReceiveMultipartStrings()); } }
public void Monitoring() { var listeningEvent = new ManualResetEvent(false); var acceptedEvent = new ManualResetEvent(false); var connectedEvent = new ManualResetEvent(false); using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) using (var poller = new Poller { PollTimeout = TestPollTimeoutMillis }) using (var repMonitor = new NetMQMonitor(rep, "inproc://rep.inproc", SocketEvents.Accepted | SocketEvents.Listening)) using (var reqMonitor = new NetMQMonitor(req, "inproc://req.inproc", SocketEvents.Connected)) { repMonitor.Accepted += (s, e) => acceptedEvent.Set(); repMonitor.Listening += (s, e) => listeningEvent.Set(); repMonitor.AttachToPoller(poller); int port = rep.BindRandomPort("tcp://127.0.0.1"); reqMonitor.Connected += (s, e) => connectedEvent.Set(); reqMonitor.AttachToPoller(poller); poller.PollTillCancelledNonBlocking(); req.Connect("tcp://127.0.0.1:" + port); req.SendFrame("a"); rep.SkipFrame(); rep.SendFrame("b"); req.SkipFrame(); Assert.IsTrue(listeningEvent.WaitOne(300)); Assert.IsTrue(connectedEvent.WaitOne(300)); Assert.IsTrue(acceptedEvent.WaitOne(300)); poller.CancelAndJoin(); } }
public void CycleCreateTerminate() { NetMQConfig.ContextCreate(true); var isTerminated = VerifyTermination(); Assert.AreEqual(false, isTerminated); // We use the Poller Test code. using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) using (var poller = new NetMQPoller { rep }) { var port = rep.BindRandomPort("tcp://127.0.0.1"); req.Connect("tcp://127.0.0.1:" + port); rep.ReceiveReady += (s, e) => { bool more; Assert.AreEqual("Hello", e.Socket.ReceiveFrameString(out more)); Assert.False(more); e.Socket.SendFrame("World"); }; poller.RunAsync(); req.SendFrame("Hello"); bool more2; Assert.AreEqual("World", req.ReceiveFrameString(out more2)); Assert.IsFalse(more2); poller.Stop(); } NetMQConfig.ContextTerminate(); isTerminated = VerifyTermination(); Assert.AreEqual(true, isTerminated); }
public void Monitoring() { using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) using (var monitor = new NetMQMonitor(rep, $"inproc://rep.inproc", SocketEvents.Accepted | SocketEvents.Listening)) { var listening = false; var accepted = false; monitor.Accepted += (s, a) => { accepted = true; }; monitor.Listening += (s, a) => { listening = true; }; monitor.Timeout = TimeSpan.FromMilliseconds(100); var monitorTask = Task.Factory.StartNew(monitor.Start); Thread.Sleep(10); var port = rep.BindRandomPort("tcp://127.0.0.1"); req.Connect("tcp://127.0.0.1:" + port); req.SendFrame("a"); rep.SkipFrame(); rep.SendFrame("b"); req.SkipFrame(); Thread.Sleep(200); Assert.IsTrue(listening); Assert.IsTrue(accepted); monitor.Stop(); Thread.Sleep(200); Assert.IsTrue(monitorTask.IsCompleted); } }
public void TestKeepAlive() { // there is no way to test tcp keep alive without disconnect the cable, we just testing that is not crashing the system using (var rep = new ResponseSocket()) using (var req = new RequestSocket()) { rep.Options.TcpKeepalive = true; rep.Options.TcpKeepaliveIdle = TimeSpan.FromSeconds(5); rep.Options.TcpKeepaliveInterval = TimeSpan.FromSeconds(1); req.Options.TcpKeepalive = true; req.Options.TcpKeepaliveIdle = TimeSpan.FromSeconds(5); req.Options.TcpKeepaliveInterval = TimeSpan.FromSeconds(1); var port = rep.BindRandomPort("tcp://127.0.0.1"); req.Connect("tcp://127.0.0.1:" + port); bool more; req.SendFrame("1"); Assert.AreEqual("1", rep.ReceiveFrameString(out more)); Assert.IsFalse(more); rep.SendFrame("2"); Assert.AreEqual("2", req.ReceiveFrameString(out more)); Assert.IsFalse(more); Assert.IsTrue(req.Options.TcpKeepalive); Assert.AreEqual(TimeSpan.FromSeconds(5), req.Options.TcpKeepaliveIdle); Assert.AreEqual(TimeSpan.FromSeconds(1), req.Options.TcpKeepaliveInterval); Assert.IsTrue(rep.Options.TcpKeepalive); Assert.AreEqual(TimeSpan.FromSeconds(5), rep.Options.TcpKeepaliveIdle); Assert.AreEqual(TimeSpan.FromSeconds(1), rep.Options.TcpKeepaliveInterval); } }
/// <summary> /// Start the ZeroMQ server /// </summary> public void Start() { if (Port.Length != 0) { Server = new ResponseSocket(); int randomPort = Server.BindRandomPort("tcp://127.0.0.1"); using MemoryMappedViewAccessor viewAccessor = _portshare.CreateViewAccessor(); byte[] bytes = BitConverter.GetBytes(randomPort); try { viewAccessor.WriteArray(0, bytes, 0, bytes.Length); } catch (Exception ex) { Logger.Error("could not bind socket to port: {0}", ex.Message); } Logger.Info("socket bound to port: {0}", randomPort); } else { Server = new ResponseSocket("tcp://127.0.0.1:" + Port); Logger.Info("socket bound to port: {0}", Port); } Poller = new NetMQPoller { Server }; Server.ReceiveReady += (s, a) => { string msg = a.Socket.ReceiveFrameString(); Logger.Debug("received message: {0}", msg); try { MessageParser.Parse(new List <string>() { msg }, (message) => { bool sent = a.Socket.TrySendFrame(new TimeSpan(10000000), message); if (!sent) { Logger.Error("could not send response: timeout"); } }, Service); } catch (Exception ex) { Logger.Error(ex, $"exception while processing command {msg}"); try { bool sent = a.Socket.TrySendFrame(new TimeSpan(10000000), new ApiResponse() { StatusCode = StatusCode.Err, Message = ex.Message }.ToString()); if (!sent) { Logger.Error("could not send response: timeout"); } } catch (Exception exErr) { Logger.Error(exErr, "could not send error response:"); } } }; PollTask = Task.Run(() => { try { Poller.Run(); } catch (Exception ex) { Logger.Error(ex, "ZMQ Poller died"); Environment.Exit(-1); } }); Logger.Info("started server (polling)"); }