private static void WorkerTaskB(object portNumber) { using (var worker = new DealerSocket()) { worker.Options.Identity = Encoding.Unicode.GetBytes("B"); worker.Connect($"tcp://localhost:{portNumber}"); int total = 0; bool end = false; while (!end) { string request = worker.ReceiveFrameString(); if (request == "END") { end = true; } else { total++; } } Console.WriteLine("B Received: {0}", total); } }
public void Start() { _server.Bind(_localConnectionString); _poller.Add(_server); _poller.RunAsync(); foreach (var connStr in _peerConnectionStrings) { DealerSocket peer = new DealerSocket(); peer.Options.Identity = _nodeId.ToByteArray(); peer.ReceiveReady += Peer_ReceiveReady; peer.Connect(connStr); _poller.Add(peer); peer.SendFrame(ConvertOp(MessageOp.Ping)); } _houseKeeper = new NetMQTimer(TimeSpan.FromSeconds(30)); _houseKeeper.Elapsed += HouseKeeper_Elapsed; _poller.Add(_houseKeeper); _houseKeeper.Enable = true; }
// Dealer-Receive接收信息 private void ThreadDealerReceive() { using (DealerSocket dealerSocket = new DealerSocket()) { dealerSocket.Options.Identity = Encoding.UTF8.GetBytes(PublicData.SessionId); dealerSocket.Connect(MQConfig.RouterSendServer); while (!PublicData.CancellationToken.IsCancellationRequested) { try { KeyData kd = dealerSocket.DealerReceive(); MqDealerReceiveEvent?.Invoke(kd); Task.Factory.StartNew(() => HandleKeyData_DealerReceive(kd.Key, kd.DataString)); } catch (Exception ex) { LogUtil.Error($"Dealer-Receive消息执行异常:{ex.Message}"); } } } }
public void Mandatory() { using (var router = new RouterSocket()) { router.Options.RouterMandatory = true; router.Bind("tcp://127.0.0.1:5555"); using (var dealer = new DealerSocket()) { dealer.Options.Identity = Encoding.ASCII.GetBytes("1"); dealer.Connect("tcp://127.0.0.1:5555"); dealer.SendFrame("Hello"); Assert.AreEqual("1", router.ReceiveFrameString()); Assert.AreEqual("Hello", router.ReceiveFrameString()); } Thread.Sleep(100); Assert.Throws <HostUnreachableException>(() => router.SendMoreFrame("1").SendFrame("Hello")); } }
public void Handover() { using (var router = new RouterSocket()) using (var dealer1 = new DealerSocket()) { router.Options.RouterHandover = true; router.Bind("inproc://127.0.0.1:5555"); dealer1.Options.Identity = Encoding.ASCII.GetBytes("ID"); dealer1.Connect("inproc://127.0.0.1:5555"); dealer1.SendMoreFrame("Hello").SendFrame("World"); var identity = router.ReceiveFrameString(); Assert.AreEqual("ID", identity); using (var dealer2 = new DealerSocket()) { dealer2.Options.Identity = Encoding.ASCII.GetBytes("ID"); dealer2.Connect("inproc://127.0.0.1:5555"); // We have new peer which should take over, however we are still reading a message var message = router.ReceiveFrameString(); Assert.AreEqual("Hello", message); message = router.ReceiveFrameString(); Assert.AreEqual("World", message); dealer2.SendMoreFrame("Hello").SendFrame("World"); identity = router.ReceiveFrameString(); Assert.AreEqual("ID", identity); message = router.ReceiveFrameString(); Assert.AreEqual("Hello", message); message = router.ReceiveFrameString(); Assert.AreEqual("World", message); } } }
private IStateReply GetStateOfTheWorld() { using (var dealer = new DealerSocket()) { var request = new StateRequest() { Subject = _configuration.Subject, }; var requestBytes = _eventSerializer.Serializer.Serialize(request); dealer.Connect(_configuration.StateOfTheWorldEndpoint); dealer.SendFrame(requestBytes); var hasResponse = dealer.TryReceiveFrameBytes(_configuration.StateCatchupTimeout, out var responseBytes); if (!hasResponse) { throw new Exception("unable to reach broker"); } return(_eventSerializer.Serializer.Deserialize <StateReply>(responseBytes)); } }
public void ClientDealer_VentilatorRouter_ProcessorsRouter() { var endpointCommand = "inproc://127.0.0.1:5000"; var endpointQuery = "inproc://127.0.0.1:5001"; var endpointVentilator = "inproc://127.0.0.1:5100"; var command = new RouterSocket(); command.ReceiveReady += (sender, args) => { _testOutputHelper.WriteLine("New connection: {0}", args.Socket.Options.Identity.ToString()); }; command.Options.Identity = Encoding.UTF8.GetBytes("COMMAND"); command.Options.RouterMandatory = true; command.Bind(endpointCommand); _testOutputHelper.WriteLine("Bind command"); Task.Delay(1000); var query = new RouterSocket(); query.ReceiveReady += (sender, args) => { _testOutputHelper.WriteLine("New connection: {0}", args.Socket.Options.Identity.ToString()); }; query.Options.Identity = Encoding.UTF8.GetBytes("QUERY"); query.Options.RouterMandatory = true; query.Bind(endpointQuery); _testOutputHelper.WriteLine("Bind query"); Task.Delay(2000); var ventilatorCommand = new DealerSocket(); ventilatorCommand.Options.Identity = Encoding.UTF8.GetBytes("VENTILATORCOMMAND"); ventilatorCommand.Connect(endpointCommand); _testOutputHelper.WriteLine("Connect to command"); Task.Delay(1000); VentilatorCommand_SendCommand(ventilatorCommand, command); Task.Delay(1000); var ventilatorQuery = new DealerSocket(); ventilatorQuery.Options.Identity = Encoding.UTF8.GetBytes("VENTILATORQUERY"); ventilatorQuery.Connect(endpointQuery); _testOutputHelper.WriteLine("Connect to query"); Task.Delay(1000); VentilatorQuery_SendQuery(ventilatorQuery, query); Task.Delay(1000); var ventilator = new RouterSocket(); ventilator.Options.Identity = Encoding.UTF8.GetBytes("VENTILATOR"); ventilator.Bind(endpointVentilator); _testOutputHelper.WriteLine("Bind Ventilator"); Task.Delay(1000); var client = new DealerSocket(); client.Options.Identity = Encoding.UTF8.GetBytes("CLIENT"); client.Connect(endpointVentilator); _testOutputHelper.WriteLine("Connect to Ventilator"); Task.Delay(1000); ClientCommand_Ventilator(client, ventilator, ventilatorCommand, command); }
public void Router_Dealer_Demonstrating_Messages_From_Publisher_To_Subscribers() { // NOTES // 1. Use ThreadLocal<DealerSocket> where each thread has // its own client DealerSocket to talk to server // 2. Each thread can send using it own socket // 3. Each thread socket is added to poller const int delay = 500; // millis var clientSocketPerThread = new ThreadLocal <DealerSocket>(); string endpoint; using (var server = new RouterSocket("@tcp://127.0.0.1:0")) // If we specify 0, it will choose a random port for us. { endpoint = server.Options.LastEndpoint; // Lets us know which port was chosen. Console.Write("Last endpoint, including port: {0}\n", server.Options.LastEndpoint); using (var poller = new NetMQPoller()) { // Start some threads, each with its own DealerSocket // to talk to the server socket. Creates lots of sockets, // but no nasty race conditions no shared state, each // thread has its own socket, happy days. for (var i = 0; i < 4; i++) { Task.Factory.StartNew(state => { DealerSocket client = null; if (!clientSocketPerThread.IsValueCreated) { client = new DealerSocket(); client.Options.Identity = Encoding.Unicode.GetBytes(state.ToString()); client.Connect(endpoint); //client.ReceiveReady += Client_ReceiveReady; clientSocketPerThread.Value = client; poller.Add(client); } else { client = clientSocketPerThread.Value; } Thread.Sleep(3000); // Wait until server is up. client.SendFrame("Ping"); while (true) { Console.Write("Client {0}: Waiting for ping...\n", i); // Work around "feature" of router/dealer: the publisher does not know the subscriber exists, until it // sends at least one message which makes it necessary to open the connection. I believe this is a // low-level feature of the TCP/IP transport. var clientMessage = client.ReceiveMultipartMessage(); Console.WriteLine("======================================"); Console.WriteLine(" INCOMING CLIENT MESSAGE FROM SERVER"); Console.WriteLine("======================================"); PrintFrames("Server receiving", clientMessage); } }, string.Format("client {0}", i), TaskCreationOptions.LongRunning); } // start the poller poller.RunAsync(); // server loop var sequenceNo = 0; for (var i = 0; i < 10; i++) { var messageToServer = new NetMQMessage(); messageToServer.AppendEmptyFrame(); messageToServer.Append(sequenceNo.ToString()); sequenceNo++; Console.WriteLine("======================================"); Console.WriteLine(" OUTGOING MESSAGE {0} TO CLIENTS ", sequenceNo); Console.WriteLine("======================================"); PrintFrames("Client Sending", messageToServer); server.SendMultipartMessage(messageToServer); Thread.Sleep(delay); } Console.WriteLine("Finished."); } } }
public DealerRouter() { const int delay = 3000; //Keep dealersocket reference within each three threads var clientSocketPerThread = new ThreadLocal <DealerSocket>(); using (var server = new RouterSocket("tcp://127.0.0.1:5556")) using (var poller = new NetMQPoller()) { for (int i = 0; i < 3; i++) { Task.Factory.StartNew(state => { DealerSocket client = null; if (!clientSocketPerThread.IsValueCreated) { client = new DealerSocket(); client.Options.Identity = Encoding.Unicode.GetBytes(state.ToString()); client.Connect("tcp://127.0.0.1:5556"); client.ReceiveReady += Client_ReceivedReady; clientSocketPerThread.Value = client; poller.Add(client); } else { client = clientSocketPerThread.Value; } //the dealersocket will provide an identity for message when it is created while (true) { var messageToServer = new NetMQMessage(); messageToServer.AppendEmptyFrame(); messageToServer.Append(state.ToString()); Console.WriteLine("======================================"); Console.WriteLine(" OUTGOING MESSAGE TO SERVER "); Console.WriteLine("======================================"); PrintFrames("Client Sending", messageToServer); client.SendMultipartMessage(messageToServer); Thread.Sleep(delay); } }, string.Format("client {0}", i), TaskCreationOptions.LongRunning); } poller.RunAsync(); while (true) { var clientMessage = server.ReceiveMultipartMessage(); Console.WriteLine("======================================"); Console.WriteLine(" INCOMING CLIENT MESSAGE FROM CLIENT "); Console.WriteLine("======================================"); PrintFrames("Server receiving", clientMessage); if (clientMessage.FrameCount == 3) { var clientAddress = clientMessage[0]; var clientOriginalMessage = clientMessage[2].ConvertToString(); string response = string.Format("{0} back from server {1} address {2}", clientOriginalMessage, DateTime.Now.ToLongTimeString(), clientAddress.ConvertToString()); var messageToClient = new NetMQMessage(); messageToClient.Append(clientAddress); messageToClient.AppendEmptyFrame(); messageToClient.Append(response); server.SendMultipartMessage(messageToClient); } } } }
public void AddSocketAfterRemoving() { using (var router1 = new RouterSocket()) using (var router2 = new RouterSocket()) using (var router3 = new RouterSocket()) using (var dealer1 = new DealerSocket()) using (var dealer2 = new DealerSocket()) using (var dealer3 = new DealerSocket()) using (var poller = new Poller(router1, router2) { PollTimeout = TestPollTimeoutMillis }) { int port1 = router1.BindRandomPort("tcp://127.0.0.1"); int port2 = router2.BindRandomPort("tcp://127.0.0.1"); int port3 = router3.BindRandomPort("tcp://127.0.0.1"); dealer1.Connect("tcp://127.0.0.1:" + port1); dealer2.Connect("tcp://127.0.0.1:" + port2); dealer3.Connect("tcp://127.0.0.1:" + port3); bool router1Arrived = false; bool router2Arrived = false; bool router3Arrived = false; var signal1 = new ManualResetEvent(false); var signal2 = new ManualResetEvent(false); var signal3 = new ManualResetEvent(false); router1.ReceiveReady += (s, e) => { router1Arrived = true; router1.SkipFrame(); router1.SkipFrame(); poller.RemoveSocket(router1); signal1.Set(); }; router2.ReceiveReady += (s, e) => { router2Arrived = true; router2.SkipFrame(); router2.SkipFrame(); poller.AddSocket(router3); signal2.Set(); }; router3.ReceiveReady += (s, e) => { router3Arrived = true; router3.SkipFrame(); router3.SkipFrame(); signal3.Set(); }; poller.PollTillCancelledNonBlocking(); dealer1.SendFrame("1"); Assert.IsTrue(signal1.WaitOne(300)); dealer2.SendFrame("2"); Assert.IsTrue(signal2.WaitOne(300)); dealer3.SendFrame("3"); Assert.IsTrue(signal3.WaitOne(300)); poller.CancelAndJoin(); Assert.IsTrue(router1Arrived); Assert.IsTrue(router2Arrived); Assert.IsTrue(router3Arrived); } }
private static void Main() { const int messageCount = 1000000; const int dealerCount = 100; Console.WriteLine("Sending {0} messages to {1} dealers", messageCount, dealerCount); //BufferPool.SetBufferManagerBufferPool(1024 * 1024 * 10, 1024); using (var router = new RouterSocket()) { router.Options.SendHighWatermark = 0; router.Bind("tcp://*:5555"); var dealers = new List<DealerSocket>(); var identities = new List<Msg>(); var random = new Random(); var identity = new byte[50]; for (var i = 0; i < dealerCount; i++) { random.NextBytes(identity); var dealer = new DealerSocket { Options = { Identity = identity.Skip(10).ToArray(), ReceiveHighWatermark = 0 } }; dealer.Connect("tcp://localhost:5555"); dealers.Add(dealer); var msg = new Msg(); msg.InitGC(identity, 10, identity.Length); // test offsets identities.Add(msg); } Thread.Sleep(500); while (!Console.KeyAvailable) { Thread.Sleep(500); var stopwatch = Stopwatch.StartNew(); for (var i = 0; i < messageCount; i++) { var msg = identities[i%identities.Count]; router.Send(ref msg, true); var msg2 = new Msg(); msg2.InitPool(1); msg2.Put((byte) 'E'); router.Send(ref msg2, false); } stopwatch.Stop(); Console.WriteLine("{0:N1} messages sent per second", messageCount/stopwatch.Elapsed.TotalSeconds); } foreach (var dealerSocket in dealers) dealerSocket.Dispose(); } }
public void Unbind(string protocol) { using (var server = new DealerSocket()) { string address1, address2; // just making sure can bind on both addresses using (var client1 = new DealerSocket()) using (var client2 = new DealerSocket()) { if (protocol == "tcp") { var port1 = server.BindRandomPort("tcp://localhost"); var port2 = server.BindRandomPort("tcp://localhost"); address1 = "tcp://localhost:" + port1; address2 = "tcp://localhost:" + port2; client1.Connect(address1); client2.Connect(address2); } else { Debug.Assert(protocol == "inproc"); address1 = "inproc://localhost1"; address2 = "inproc://localhost2"; server.Bind(address1); server.Bind(address2); client1.Connect(address1); client2.Connect(address2); } Thread.Sleep(100); // we should be connected to both server client1.SendFrame("1"); client2.SendFrame("2"); // the server receive from both server.SkipFrame(); server.SkipFrame(); } // unbind second address server.Unbind(address2); Thread.Sleep(100); using (var client1 = new DealerSocket()) using (var client2 = new DealerSocket()) { client1.Options.DelayAttachOnConnect = true; client1.Connect(address1); client2.Options.DelayAttachOnConnect = true; if (protocol == "tcp") { client2.Connect(address2); client1.SendFrame("1"); server.SkipFrame(); Assert.IsFalse(client2.TrySendFrame(TimeSpan.FromSeconds(2), "2")); } else { Assert.Throws <EndpointNotFoundException>(() => { client2.Connect(address2); }); } } } }
public void Do() { using (var socket = new DealerSocket()) { socket.Connect("tcp://127.0.0.1:5556"); SecureChannel secureChannel = SecureChannel.CreateClientSecureChannel(null, m_configuration); // we are not using signed certificate so we need to validate // the certificate of the server, by default the secure channel // is checking that the source of the // certitiface is a root certificate authority //secureChannel.SetVerifyCertificate(c => true); // we need to set X509Certificate with a private key for the server X509Certificate2 certificate = new X509Certificate2( System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "server.crt"), "1234"); secureChannel.Certificate = certificate; List <NetMQMessage> outgoingMessages = new List <NetMQMessage>(); // call the process message with null as the incoming message // because the client is initiating the connection secureChannel.ProcessMessage(null, outgoingMessages); //Server.SendMessages(socket, outgoingMessages); foreach (NetMQMessage message in outgoingMessages) { socket.SendMultipartMessage(message); } outgoingMessages.Clear(); // waiting for a message from the server NetMQMessage incomingMessage = socket.ReceiveMultipartMessage(); // calling ProcessMessage until ProcessMessage return true // and the SecureChannel is ready to encrypt and decrypt messages while (!secureChannel.ProcessMessage(incomingMessage, outgoingMessages)) { foreach (NetMQMessage message in outgoingMessages) { socket.SendMultipartMessage(message); } outgoingMessages.Clear(); //Server.SendMessages(socket, outgoingMessages); incomingMessage = socket.ReceiveMultipartMessage(); } foreach (NetMQMessage message in outgoingMessages) { socket.SendMultipartMessage(message); } outgoingMessages.Clear(); //Server.SendMessages(socket, outgoingMessages); // you can now use the secure channel to encrypt messages NetMQMessage plainMessage = new NetMQMessage(); plainMessage.Append("Hello"); // encrypting the message and sending it over the socket socket.SendMultipartMessage(secureChannel.EncryptApplicationMessage(plainMessage)); NetMQMessage cipherMessage = socket.ReceiveMultipartMessage(); // decrypting the message plainMessage = secureChannel.DecryptApplicationMessage(cipherMessage); System.Console.WriteLine(plainMessage.First.ConvertToString()); } }
public NetMQRequestor(string connString) { clientSocket = new DealerSocket(); connectionString = connString; clientSocket.Connect(connString); }
public void RemoveSocket() { using (var router1 = new RouterSocket()) using (var router2 = new RouterSocket()) using (var router3 = new RouterSocket()) using (var dealer1 = new DealerSocket()) using (var dealer2 = new DealerSocket()) using (var dealer3 = new DealerSocket()) using (var poller = new NetMQPoller { router1, router2, router3 }) { int port1 = router1.BindRandomPort("tcp://127.0.0.1"); int port2 = router2.BindRandomPort("tcp://127.0.0.1"); int port3 = router3.BindRandomPort("tcp://127.0.0.1"); dealer1.Connect("tcp://127.0.0.1:" + port1); dealer2.Connect("tcp://127.0.0.1:" + port2); dealer3.Connect("tcp://127.0.0.1:" + port3); bool first = true; router1.ReceiveReady += (s, e) => { if (!first) { Assert.Fail("This should not happen because we cancelled the socket"); } first = false; // identity e.Socket.SkipFrame(); bool more; Assert.AreEqual("Hello", e.Socket.ReceiveFrameString(out more)); Assert.False(more); // cancelling the socket poller.Remove(e.Socket); // remove self }; router2.ReceiveReady += (s, e) => { // identity byte[] identity = e.Socket.ReceiveFrameBytes(); // message e.Socket.SkipFrame(); e.Socket.SendMoreFrame(identity); e.Socket.SendFrame("2"); }; router3.ReceiveReady += (s, e) => { // identity byte[] identity = e.Socket.ReceiveFrameBytes(); // message e.Socket.SkipFrame(); e.Socket.SendMoreFrame(identity).SendFrame("3"); }; Task pollerTask = Task.Factory.StartNew(poller.Run); // Send three messages. Only the first will be processed, as then handler removes // the socket from the poller. dealer1.SendFrame("Hello"); dealer1.SendFrame("Hello2"); dealer1.SendFrame("Hello3"); // making sure the socket defined before the one cancelled still works dealer2.SendFrame("1"); Assert.AreEqual("2", dealer2.ReceiveFrameString()); // making sure the socket defined after the one cancelled still works dealer3.SendFrame("1"); Assert.AreEqual("3", dealer3.ReceiveFrameString()); poller.Stop(); Assert.IsTrue(pollerTask.IsCompleted); } }
public void AddSocketAfterRemoving() { using (var router1 = new RouterSocket()) using (var router2 = new RouterSocket()) using (var router3 = new RouterSocket()) using (var dealer1 = new DealerSocket()) using (var dealer2 = new DealerSocket()) using (var dealer3 = new DealerSocket()) using (var poller = new NetMQPoller { router1, router2 }) { int port1 = router1.BindRandomPort("tcp://127.0.0.1"); int port2 = router2.BindRandomPort("tcp://127.0.0.1"); int port3 = router3.BindRandomPort("tcp://127.0.0.1"); dealer1.Connect("tcp://127.0.0.1:" + port1); dealer2.Connect("tcp://127.0.0.1:" + port2); dealer3.Connect("tcp://127.0.0.1:" + port3); bool router1Arrived = false; bool router2Arrived = false; bool router3Arrived = false; var signal1 = new ManualResetEvent(false); var signal2 = new ManualResetEvent(false); var signal3 = new ManualResetEvent(false); router1.ReceiveReady += (s, e) => { router1Arrived = true; router1.SkipFrame(); router1.SkipFrame(); poller.Remove(router1); signal1.Set(); }; router2.ReceiveReady += (s, e) => { router2Arrived = true; router2.SkipFrame(); router2.SkipFrame(); poller.Add(router3); signal2.Set(); }; router3.ReceiveReady += (s, e) => { router3Arrived = true; router3.SkipFrame(); router3.SkipFrame(); signal3.Set(); }; poller.RunAsync(); dealer1.SendFrame("1"); Assert.IsTrue(signal1.WaitOne(300)); dealer2.SendFrame("2"); Assert.IsTrue(signal2.WaitOne(300)); dealer3.SendFrame("3"); Assert.IsTrue(signal3.WaitOne(300)); poller.Stop(); Assert.IsTrue(router1Arrived); Assert.IsTrue(router2Arrived); Assert.IsTrue(router3Arrived); } }
/// <summary> /// Create the DEALER socket and connect it to QUEUE backend. /// Set the identity. /// Send the initial READY message. /// </summary> private static DealerSocket GetWorkerSocket(bool verbose, int id) { var worker = new DealerSocket { Options = { Identity = Encoding.UTF8.GetBytes("Worker_" + id) } }; worker.Connect(Commons.QueueBackend); if (verbose) Console.WriteLine("[WORKER] {0} sending 'READY'.", Encoding.UTF8.GetString(worker.Options.Identity)); // send READY worker.SendFrame(Commons.PPPReady); return worker; }
public XplaneConnectionManager(IEventBroker broker, IAppConfig config, IFsdManger fsdManager) : base(broker) { DealerSocket visualDealerSocket = null; mVisualDealerSockets = null; mConfig = config; mFsdManager = fsdManager; if (mConfig.VisualClientIPs.Count > 0) { foreach (string mIP in mConfig.VisualClientIPs) { visualDealerSocket = new DealerSocket(); visualDealerSocket.Options.Identity = Encoding.UTF8.GetBytes("CLIENT"); visualDealerSocket.Options.TcpKeepalive = true; try { visualDealerSocket.Connect("tcp://" + mIP + ":" + mConfig.TcpPort); if (mVisualDealerSockets == null) { mVisualDealerSockets = new List <DealerSocket>(); } mVisualDealerSockets.Add(visualDealerSocket); } catch (AddressAlreadyInUseException) { NotificationPosted?.Invoke(this, new NotificationPostedEventArgs(NotificationType.Error, "Plugin port already in use. Please choose a different TCP port.")); } } } if (!string.IsNullOrEmpty(mConfig.SimClientIP)) { mSimulatorIP = mConfig.SimClientIP; } mMessageQueue = new NetMQQueue <string>(); mDealerSocket = new DealerSocket(); mDealerSocket.Options.TcpKeepalive = true; mDealerSocket.Options.Identity = Encoding.UTF8.GetBytes("CLIENT"); mDealerSocket.ReceiveReady += DealerSocket_ReceiveReady; try { mDealerSocket.Connect("tcp://" + mSimulatorIP + ":" + mConfig.TcpPort); } catch (AddressAlreadyInUseException) { NotificationPosted?.Invoke(this, new NotificationPostedEventArgs(NotificationType.Error, "Plugin port already in use. Please choose a different TCP port.")); } mPoller = new NetMQPoller { mDealerSocket, mMessageQueue }; if (!mPoller.IsRunning) { mPoller.RunAsync(); } mMessageQueue.ReceiveReady += (s, e) => { if (mMessageQueue.TryDequeue(out string msg, TimeSpan.FromMilliseconds(100))) { if (mDealerSocket != null) { mDealerSocket.SendFrame(msg); } if (mVisualDealerSockets != null && mVisualDealerSockets.Count > 0) { foreach (DealerSocket socket in mVisualDealerSockets) { socket.SendFrame(msg); } } } }; mXplaneConnector = new XPlaneConnector.XPlaneConnector(mSimulatorIP); mUserAircraftData = new UserAircraftData(); mRadioStackState = new UserAircraftRadioStack(); mGetXplaneDataTimer = new Timer { Interval = 10 }; mGetXplaneDataTimer.Tick += GetXplaneDataTimer_Tick; mGetXplaneDataTimer.Start(); mConnectionTimer = new Timer { Interval = 50 }; mConnectionTimer.Tick += ConnectionTimer_Tick; mConnectionTimer.Start(); mRetryConnectionTimer = new Timer { Interval = 1000 }; mRetryConnectionTimer.Tick += RetryConnectionTimer_Tick; mRetryConnectionTimer.Start(); mWhosOnlineListRefresh = new Timer { Interval = 5000 }; mWhosOnlineListRefresh.Tick += WhosOnlineListRefresh_Tick; SetupSubscribers(); if (!Directory.Exists(Path.Combine(mConfig.AppPath, "PluginLogs"))) { Directory.CreateDirectory(Path.Combine(mConfig.AppPath, "PluginLogs")); } var directory = new DirectoryInfo(Path.Combine(mConfig.AppPath, "PluginLogs")); var query = directory.GetFiles("*", SearchOption.AllDirectories); foreach (var file in query.OrderByDescending(file => file.CreationTime).Skip(10)) { file.Delete(); } mRawDataStream = new StreamWriter(Path.Combine(mConfig.AppPath, string.Format($"PluginLogs/PluginLog-{DateTime.UtcNow:yyyyMMddHHmmss}.log")), false); }
public void Run() { //NOTES //1. Use ThreadLocal<DealerSocket> where each thread has // its own client DealerSocket to talk to server //2. Each thread can send using it own socket //3. Each thread socket is added to poller ThreadLocal <DealerSocket> clientSocketPerThread = new ThreadLocal <DealerSocket>(); int delay = 3000; Poller poller = new Poller(); using (NetMQContext ctx = NetMQContext.Create()) { using (var server = ctx.CreateRouterSocket()) { server.Bind("tcp://127.0.0.1:5556"); //start some threads, each with its own DealerSocket //to talk to the server socket. Creates lots of sockets, //but no nasty race conditions no shared state, each //thread has its own socket, happy days for (int i = 0; i < 3; i++) { Task.Factory.StartNew((state) => { DealerSocket client = null; if (!clientSocketPerThread.IsValueCreated) { client = ctx.CreateDealerSocket(); client.Connect("tcp://127.0.0.1:5556"); client.ReceiveReady += Client_ReceiveReady; clientSocketPerThread.Value = client; poller.AddSocket(client); } else { client = clientSocketPerThread.Value; } while (true) { var messageToServer = new NetMQMessage(); messageToServer.AppendEmptyFrame(); messageToServer.Append(state.ToString()); client.SendMessage(messageToServer); Thread.Sleep(delay); } }, string.Format("client {0}", i), TaskCreationOptions.LongRunning); } //start the poller Task task = Task.Factory.StartNew(poller.Start); //server loop while (true) { var clientMessage = server.ReceiveMessage(); Console.WriteLine("========================"); Console.WriteLine(" INCOMING CLIENT MESSAGE "); Console.WriteLine("========================"); for (int i = 0; i < clientMessage.FrameCount; i++) { Console.WriteLine("Frame[{0}] = {1}", i, clientMessage[i].ConvertToString()); } if (clientMessage.FrameCount == 3) { var clientAddress = clientMessage[0]; var clientOriginalMessage = clientMessage[2].ConvertToString(); string response = string.Format("{0} back from server {1}", clientOriginalMessage, DateTime.Now.ToLongTimeString()); var messageToClient = new NetMQMessage(); messageToClient.Append(clientAddress); messageToClient.AppendEmptyFrame(); messageToClient.Append(response); server.SendMessage(messageToClient); } } } } }
public void AddTwoSocketAfterRemoving() { using (var router1 = new RouterSocket()) using (var router2 = new RouterSocket()) using (var router3 = new RouterSocket()) using (var router4 = new RouterSocket()) using (var dealer1 = new DealerSocket()) using (var dealer2 = new DealerSocket()) using (var dealer3 = new DealerSocket()) using (var dealer4 = new DealerSocket()) using (var poller = new NetMQPoller { router1, router2 }) { int port1 = router1.BindRandomPort("tcp://127.0.0.1"); int port2 = router2.BindRandomPort("tcp://127.0.0.1"); int port3 = router3.BindRandomPort("tcp://127.0.0.1"); int port4 = router4.BindRandomPort("tcp://127.0.0.1"); dealer1.Connect("tcp://127.0.0.1:" + port1); dealer2.Connect("tcp://127.0.0.1:" + port2); dealer3.Connect("tcp://127.0.0.1:" + port3); dealer4.Connect("tcp://127.0.0.1:" + port4); int router1Arrived = 0; int router2Arrived = 0; bool router3Arrived = false; bool router4Arrived = false; var signal1 = new ManualResetEvent(false); var signal2 = new ManualResetEvent(false); var signal3 = new ManualResetEvent(false); var signal4 = new ManualResetEvent(false); router1.ReceiveReady += (s, e) => { router1Arrived++; router1.SkipFrame(); // identity router1.SkipFrame(); // message poller.Remove(router1); signal1.Set(); }; router2.ReceiveReady += (s, e) => { router2Arrived++; router2.SkipFrame(); // identity router2.SkipFrame(); // message if (router2Arrived == 1) { poller.Add(router3); poller.Add(router4); signal2.Set(); } }; router3.ReceiveReady += (s, e) => { router3.SkipFrame(); // identity router3.SkipFrame(); // message router3Arrived = true; signal3.Set(); }; router4.ReceiveReady += (s, e) => { router4.SkipFrame(); // identity router4.SkipFrame(); // message router4Arrived = true; signal4.Set(); }; poller.RunAsync(); dealer1.SendFrame("1"); Assert.IsTrue(signal1.WaitOne(300)); dealer2.SendFrame("2"); Assert.IsTrue(signal2.WaitOne(300)); dealer3.SendFrame("3"); dealer4.SendFrame("4"); dealer2.SendFrame("2"); dealer1.SendFrame("1"); Assert.IsTrue(signal3.WaitOne(300)); Assert.IsTrue(signal4.WaitOne(300)); poller.Stop(); router1.SkipFrame(); bool more; Assert.AreEqual("1", router1.ReceiveFrameString(out more)); Assert.IsFalse(more); Assert.AreEqual(1, router1Arrived); Assert.AreEqual(2, router2Arrived); Assert.IsTrue(router3Arrived); Assert.IsTrue(router4Arrived); } }
private static void Main() { const int messageCount = 1000000; const int dealerCount = 100; Console.WriteLine("Sending {0} messages to {1} dealers", messageCount, dealerCount); //BufferPool.SetBufferManagerBufferPool(1024 * 1024 * 10, 1024); using (var router = new RouterSocket()) { router.Options.SendHighWatermark = 0; router.Bind("tcp://*:5555"); var dealers = new List <DealerSocket>(); var identities = new List <Msg>(); var random = new Random(); var identity = new byte[50]; for (var i = 0; i < dealerCount; i++) { random.NextBytes(identity); var dealer = new DealerSocket { Options = { Identity = identity.Skip(10).ToArray(), ReceiveHighWatermark = 0 } }; dealer.Connect("tcp://localhost:5555"); dealers.Add(dealer); var msg = new Msg(); msg.InitGC(identity, 10, identity.Length); // test offsets identities.Add(msg); } Thread.Sleep(500); while (!Console.KeyAvailable) { Thread.Sleep(500); var stopwatch = Stopwatch.StartNew(); for (var i = 0; i < messageCount; i++) { var msg = identities[i % identities.Count]; router.Send(ref msg, true); var msg2 = new Msg(); msg2.InitPool(1); msg2.Put((byte)'E'); router.Send(ref msg2, false); } stopwatch.Stop(); Console.WriteLine("{0:N1} messages sent per second", messageCount / stopwatch.Elapsed.TotalSeconds); } foreach (var dealerSocket in dealers) { dealerSocket.Dispose(); } } }
public static void Main(string[] args) { string tcp = "tcp://127.0.0.1:20000"; string inproc = "inproc://response_dealer"; ResponseSocket res = new ResponseSocket(inproc); IpcCollectorDevice ipcCollectorDevice = new IpcCollectorDevice(tcp, inproc); ipcCollectorDevice.Start(); NetMQRequestor requestor = new NetMQRequestor(tcp); var message = Guid.NewGuid().ToString(); requestor.SendMessage(message); // NOTES // 1. Use ThreadLocal<DealerSocket> where each thread has // its own client DealerSocket to talk to server // 2. Each thread can send using it own socket // 3. Each thread socket is added to poller const int delay = 10; // millis var clientSocketPerThread = new ThreadLocal <DealerSocket>(); int d = 0; using (var server = new RouterSocket("@tcp://127.0.0.1:5556")) using (var poller = new NetMQPoller()) { // Start some threads, each with its own DealerSocket // to talk to the server socket. Creates lots of sockets, // but no nasty race conditions no shared state, each // thread has its own socket, happy days. for (int i = 0; i < 3; i++) { Task.Factory.StartNew(state => { DealerSocket client = null; if (!clientSocketPerThread.IsValueCreated) { client = new DealerSocket(); client.Options.Identity = Encoding.Unicode.GetBytes(state.ToString()); client.Connect("tcp://127.0.0.1:5556"); client.ReceiveReady += Client_ReceiveReady; clientSocketPerThread.Value = client; poller.Add(client); } else { client = clientSocketPerThread.Value; } while (true) { var messageToServer = new NetMQMessage(); messageToServer.AppendEmptyFrame(); messageToServer.Append(Interlocked.Increment(ref d).ToString()); //Console.WriteLine("======================================"); //Console.WriteLine(" OUTGOING MESSAGE TO SERVER "); //Console.WriteLine("======================================"); //PrintFrames("Client Sending", messageToServer); //messageToServer.ToString(); client.SendMultipartMessage(messageToServer); Thread.Sleep(delay); } }, string.Format("client {0}", i), TaskCreationOptions.LongRunning); } // start the poller poller.RunAsync(); // server loop while (true) { string date = DateTime.Now.ToString(); var clientMessage = server.ReceiveMultipartMessage(); //Console.WriteLine("======================================"); //Console.WriteLine(" INCOMING CLIENT MESSAGE FROM CLIENT "); //Console.WriteLine("======================================"); //PrintFrames("Server receiving", clientMessage); Thread.Sleep(new Random().Next(0, 1000)); if (clientMessage.FrameCount == 3) { var clientAddress = clientMessage[0]; var clientOriginalMessage = clientMessage[2].ConvertToString(); string response = string.Format("{0} back from server {1}", clientOriginalMessage, date); var messageToClient = new NetMQMessage(); messageToClient.Append(clientAddress); messageToClient.AppendEmptyFrame(); messageToClient.Append(response); server.SendMultipartMessage(messageToClient); } } } }
public async Task <bool> RunSimulationAsync(Options options, TextWriter logger, CancellationToken token = default) { Logger = logger; try { Id = options.Id; _socket = new DealerSocket(); _socket.Options.Linger = TimeSpan.FromSeconds(30); _socket.Options.Identity = Encoding.ASCII.GetBytes(Id); if (options.Connect) { _socket.Connect(options.URL); } else { _socket.Bind(options.URL); } using (Outgoing = new NetMQQueue <NetMQMessage>()) { using var poller = new NetMQPoller() { _socket, Outgoing }; _socket.ReceiveReady += (sender, e) => { var msg = _socket.ReceiveMultipartMessage(); if (msg.FrameCount < 3) { logger.WriteLine($"Received message with only {msg.FrameCount} frames."); return; } var type = msg[1].ConvertToString(); logger.WriteLine($"Received {type} message."); switch (type) { case "crane": OnCraneMessageReceived(msg[2].Buffer); break; case "sim": OnSimMessageReceived(msg[2].Buffer); break; default: //Console.WriteLine($"Received message with unmapped type {type}"); break; } }; Outgoing.ReceiveReady += (sender, e) => { var msg = Outgoing.Dequeue(); if (_socket.TrySendMultipartMessage(TimeSpan.FromMinutes(1), msg)) // Note that for policyruns (virtual time) a lot of events are generated { logger.WriteLine($"Sent {msg[1].ConvertToString()} message."); } //else logger.WriteLine($"Discarded outgoing {msg[1].ConvertToString()} message."); }; if (!options.RunSync || options.Connect) { poller.RunAsync(); } if (!string.IsNullOrEmpty(options.SettingsPath)) { if (options.SettingsPath.Equals("Default", StringComparison.OrdinalIgnoreCase)) { logger.WriteLine("Using default settings"); _settingsReceived.SetResult(GetDefaultSettings()); } else { logger.WriteLine($"Reading settings from {options.SettingsPath}"); _settingsReceived.SetResult(File.ReadAllBytes(options.SettingsPath)); } } var result = false; try { if (!options.RunSync) { result = await RunSimulationAsync(await _settingsReceived.Task, options.PolicyRun); // wait until the outgoing queue is cleared var remaining = Outgoing.Count; while (remaining > 0) { await Task.Delay(1000, token); if (Outgoing.Count == remaining) { break; // assume nobody is listening for world states } remaining = Outgoing.Count; } } else { result = RunSimulation(await _settingsReceived.Task, options.SyncURL, options.Id); } } finally { poller.Stop(); } return(result); } } finally { DisposeSocket(); } }
public static void Main(string[] args) { // NOTES // 1. Use ThreadLocal<DealerSocket> where each thread has // its own client DealerSocket to talk to server // 2. Each thread can send using it own socket // 3. Each thread socket is added to poller const int delay = 3000; // millis var clientSocketPerThread = new ThreadLocal <DealerSocket> (); using (var server = new RouterSocket("@tcp://127.0.0.1:5556")) using (var poller = new NetMQPoller()) { // Start some threads, each with its own DealerSocket // to talk to the server socket. Creates lots of sockets, // but no nasty race conditions no shared state, each // thread has its own socket, happy days. for (int i = 0; i < 3; i++) { Task.Factory.StartNew(state => { DealerSocket client = null; if (!clientSocketPerThread.IsValueCreated) { client = new DealerSocket(); client.Options.Identity = Encoding.Unicode.GetBytes(state.ToString()); client.Connect("tcp://127.0.0.1:5556"); client.ReceiveReady += Client_ReceiveReady; clientSocketPerThread.Value = client; poller.Add(client); } else { client = clientSocketPerThread.Value; } while (true) { var messageToServer = new NetMQMessage(); messageToServer.AppendEmptyFrame(); messageToServer.Append(state.ToString()); Console.WriteLine("======================================"); Console.WriteLine(" OUTGOING MESSAGE TO SERVER "); Console.WriteLine("======================================"); PrintFrames("Client Sending", messageToServer); client.SendMultipartMessage(messageToServer); Thread.Sleep(delay); } }, string.Format("client {0}", i), TaskCreationOptions.LongRunning); } // start the poller poller.RunAsync(); // server loop while (true) { var clientMessage = server.ReceiveMultipartMessage(); Console.WriteLine("======================================"); Console.WriteLine(" INCOMING CLIENT MESSAGE FROM CLIENT "); Console.WriteLine("======================================"); PrintFrames("Server receiving", clientMessage); if (clientMessage.FrameCount == 3) { var clientAddress = clientMessage[0]; var clientOriginalMessage = clientMessage[2].ConvertToString(); string response = string.Format("{0} back from server {1}", clientOriginalMessage, DateTime.Now.ToLongTimeString()); var messageToClient = new NetMQMessage(); messageToClient.Append(clientAddress); messageToClient.AppendEmptyFrame(); messageToClient.Append(response); server.SendMultipartMessage(messageToClient); } } } void PrintFrames(string operationType, NetMQMessage message) { for (int i = 0; i < message.FrameCount; i++) { Console.WriteLine("{0} Socket : Frame[{1}] = {2}", operationType, i, message[i].ConvertToString()); } } }
static void Main(string[] args) { const int delay = 5000; // millis var clientSocketPerThread = new ThreadLocal <DealerSocket>(); using (var poller = new NetMQPoller()) { // Start some threads, each with its own DealerSocket // to talk to the server socket. Creates lots of sockets, // but no nasty race conditions no shared state, each // thread has its own socket, happy days. //for (int i = 0; i < 2; i++) //{ Task.Factory.StartNew(state => { DealerSocket client = null; if (!clientSocketPerThread.IsValueCreated) { client = new DealerSocket(); client.Options.Identity = Encoding.Unicode.GetBytes("Client 1"); client.Connect("tcp://127.0.0.1:5000"); client.ReceiveReady += Client_ReceiveReady; clientSocketPerThread.Value = client; poller.Add(client); } else { client = clientSocketPerThread.Value; } while (true) { var messageToServer = new NetMQMessage(); messageToServer.AppendEmptyFrame(); messageToServer.Append("message from client 1"); Console.WriteLine("======================================"); Console.WriteLine(" OUTGOING MESSAGE TO SERVER "); Console.WriteLine("======================================"); PrintFrames("Client Sending", messageToServer); client.SendMultipartMessage(messageToServer); Thread.Sleep(delay); } }, string.Format("client 1"), TaskCreationOptions.LongRunning); //} // start the poller poller.RunAsync(); /* * DealerSocket client = new DealerSocket("tcp://127.0.0.1:5000"); * client.Options.Identity = Encoding.Unicode.GetBytes("1"); * client.Connect("tcp://127.0.0.1:5000"); * //client.ReceiveReady += Client_ReceiveReady; * var messageToServer = new NetMQMessage(); * messageToServer.AppendEmptyFrame(); * messageToServer.Append("Hello server~"); * client.SendMultipartMessage(messageToServer); */ while (true) { ; } } }
public void HelloTest() { Action <ZreMsg> setMessage = m => { m.Id = ZreMsg.MessageId.Hello; m.Hello.Sequence = 123; m.Hello.Endpoint = "Life is short but Now lasts for ever"; m.Hello.Groups = new List <string>(); m.Hello.Groups.Add("Name: Brutus"); m.Hello.Groups.Add("Age: 43"); m.Hello.Status = 123; m.Hello.Name = "Life is short but Now lasts for ever"; m.Hello.Headers = new Dictionary <string, string>(); m.Hello.Headers.Add("Name", "Brutus"); m.Hello.Headers.Add("Age", "43"); }; Action <ZreMsg> checkMessage = m => { Assert.That(m.Id, Is.EqualTo(ZreMsg.MessageId.Hello)); Assert.That(m.Hello.Sequence, Is.EqualTo(123)); Assert.That(m.Hello.Endpoint, Is.EqualTo("Life is short but Now lasts for ever")); Assert.That(m.Hello.Groups.Count, Is.EqualTo(2)); Assert.That(m.Hello.Groups[0], Is.EqualTo("Name: Brutus")); Assert.That(m.Hello.Groups[1], Is.EqualTo("Age: 43")); Assert.That(m.Hello.Status, Is.EqualTo(123)); Assert.That(m.Hello.Name, Is.EqualTo("Life is short but Now lasts for ever")); Assert.That(m.Hello.Headers.Count, Is.EqualTo(2)); Assert.That(m.Hello.Headers["Name"], Is.EqualTo("Brutus")); Assert.That(m.Hello.Headers["Age"], Is.EqualTo("43")); }; using (var client = new DealerSocket()) using (var server = new RouterSocket()) { server.Bind("inproc://zprototestHello"); client.Connect("inproc://zprototestHello"); ZreMsg clientMessage = new ZreMsg(); ZreMsg serverMessage = new ZreMsg(); for (int i = 0; i < 2; i++) { // client send message to server setMessage(clientMessage); clientMessage.Send(client); // server receive the message serverMessage.Receive(server); // check that message received ok Assert.That(serverMessage.RoutingId, Is.Not.Null); checkMessage(serverMessage); // reply to client, no need to set the message, using client data serverMessage.Send(server); // client receive the message clientMessage.Receive(client); // check that message received ok Assert.That(clientMessage.RoutingId, Is.Null); checkMessage(clientMessage); } } }
private async Task Handler() { while (this.IsRunning) { try { using (var socket = new DealerSocket()) using (this.BackendBuffer = new NetMQQueue <TransportMessage>()) using (var poller = new NetMQPoller() { socket, this.BackendBuffer }) using (var monitor = new NetMQ.Monitoring.NetMQMonitor(socket, $"inproc://monitor.forwarderdevice.backend.{Guid.NewGuid().ToString()}", SocketEvents.Connected | SocketEvents.Disconnected)) { socket.Options.Identity = System.Text.Encoding.ASCII.GetBytes(Guid.NewGuid().ToString().Replace("-", "").ToLowerInvariant()); socket.ReceiveReady += (sender, e) => { try { var netmqMessage = new NetMQMessage(); if (e.Socket.TryReceiveMultipartMessage(ref netmqMessage)) { var message = netmqMessage.ToMessage(); this.ForwarderDevice.OnBackendReceived(message); this.ForwarderDevice.frontendBuffer.Enqueue(message); } } catch (Exception ex) { this.ForwarderDevice.OnDiagnosticMessage(ex.Message + ": " + ex.StackTrace); } }; this.BackendBuffer.ReceiveReady += (sender, e) => { try { while (this.BackendBuffer.TryDequeue(out TransportMessage message, TimeSpan.Zero)) { this.ForwarderDevice.OnFrontendForwarded(message); this.ForwarderDevice.OnDiagnosticMessage("Forwarding message to " + this.Endpoint.ToConnectionString()); if (!socket.TrySendMultipartMessage(TimeSpan.FromSeconds(1), message.ToNetMQMessage())) { this.ForwarderDevice.OnDiagnosticMessage("Failed to send message"); } } } catch (Exception ex) { this.ForwarderDevice.OnDiagnosticMessage(ex.Message + ": " + ex.StackTrace); } }; monitor.Connected += (sender, e) => { this.ForwarderDevice.OnDiagnosticMessage($"Dealer socket conntected to {this.Endpoint.ToConnectionString()}"); this.IsConnected = true; }; monitor.Disconnected += (sender, e) => { this.ForwarderDevice.OnDiagnosticMessage($"Dealer socket disconntected from {this.Endpoint.ToConnectionString()}"); this.IsConnected = false; }; this.ForwarderDevice.OnDiagnosticMessage($"Attempting to connect to {this.Endpoint.ToConnectionString()}"); monitor.StartAsync(); monitor.AttachToPoller(poller); var pollerTask = new Task(poller.Run); pollerTask.ContinueWith((Task task) => { var ex = task.Exception; this.ForwarderDevice.OnDiagnosticMessage(ex.Message + ": " + ex.StackTrace); this.IsConnected = false; }, TaskContinuationOptions.OnlyOnFaulted); pollerTask.Start(); socket.Connect(this.Endpoint.ToConnectionString()); var start = DateTime.Now; while (!this.IsConnected) { if ((DateTime.Now - start).TotalMilliseconds > 5000) { throw new Exception($"Connection timeout [{this.ServiceName}]"); } await Task.Delay(1000); } while (this.IsConnected && this.IsRunning) { await Task.Delay(1000); } this.ForwarderDevice.OnDiagnosticMessage("Closing dealer socket..."); poller.StopAsync(); socket.Disconnect(this.Endpoint.ToConnectionString()); monitor.DetachFromPoller(); monitor.Stop(); this.IsConnected = false; } if (this.IsRunning) { await Task.Delay(1000); } } catch (Exception ex) { this.ForwarderDevice.OnDiagnosticMessage(ex.Message + ": " + ex.StackTrace); } } }
public void InprocRouterDealerTest() { // The main thread simply starts several clients and a server, and then // waits for the server to finish. var readyMsg = Encoding.UTF8.GetBytes("RDY"); var freeWorkers = new Queue <byte[]>(); using (var backendsRouter = new RouterSocket()) { backendsRouter.Options.Identity = Guid.NewGuid().ToByteArray(); backendsRouter.Bind("inproc://backend"); backendsRouter.ReceiveReady += (o, e) => { // Handle worker activity on backend while (e.Socket.HasIn) { var msg = e.Socket.ReceiveMultipartMessage(); var idRouter = msg.Pop(); // forget the empty frame if (msg.First.IsEmpty) { msg.Pop(); } var id = msg.Pop(); if (msg.First.IsEmpty) { msg.Pop(); } if (msg.FrameCount == 1) { // worker send RDY message queue his Identity to the free workers queue if (readyMsg[0] == msg[0].Buffer[0] && readyMsg[1] == msg[0].Buffer[1] && readyMsg[2] == msg[0].Buffer[2]) { lock (freeWorkers) { freeWorkers.Enqueue(id.Buffer); } } } } }; using (var poller = new NetMQPoller { backendsRouter }) { for (int i = 0; i < 2; i++) { ParameterizedThreadStart threadMmethod = state => { byte[] routerId = (byte[])state; byte[] workerId = Guid.NewGuid().ToByteArray(); using (var workerSocket = new DealerSocket()) { workerSocket.Options.Identity = workerId; workerSocket.Connect("inproc://backend"); var workerReadyMsg = new NetMQMessage(); workerReadyMsg.Append(workerId); workerReadyMsg.AppendEmptyFrame(); workerReadyMsg.Append(readyMsg); workerSocket.SendMultipartMessage(workerReadyMsg); Thread.Sleep(1000); } }; var workerThread = new Thread(threadMmethod) { IsBackground = true, Name = "worker" + i }; workerThread.Start(backendsRouter.Options.Identity); } poller.RunAsync(); Thread.Sleep(1000); poller.Stop(); Assert.AreEqual(2, freeWorkers.Count); } } }
/// <summary> /// Tries to connect to the QDMS server. /// </summary> public void Connect() { Dispose(); _context = NetMQContext.Create(); _reqSocket = _context.CreateDealerSocket(); _subSocket = _context.CreateSubscriberSocket(); _dealerSocket = _context.CreateSocket(ZmqSocketType.Dealer); _reqSocket.Options.Identity = Encoding.UTF8.GetBytes(_name); _subSocket.Options.Identity = Encoding.UTF8.GetBytes(_name); _dealerSocket.Options.Identity = Encoding.UTF8.GetBytes(_name); _dealerSocket.ReceiveReady += _dealerSocket_ReceiveReady; _reqSocket.ReceiveReady += _reqSocket_ReceiveReady; _subSocket.ReceiveReady += _subSocket_ReceiveReady; _reqSocket.Connect(string.Format("tcp://{0}:{1}", _host, _realTimeRequestPort)); //start off by sending a ping to make sure everything is regular string reply = ""; try { _reqSocket.SendMore(""); _reqSocket.Send("PING"); _reqSocket.ReceiveString(TimeSpan.FromSeconds(1)); //empty frame starts the REP message //todo receive string? reply = _reqSocket.ReceiveString(TimeSpan.FromMilliseconds(50)); } catch { Dispose(); } if (reply != "PONG") //server didn't reply or replied incorrectly { _reqSocket.Disconnect(string.Format("tcp://{0}:{1}", _host, _realTimeRequestPort)); _reqSocket.Close(); { RaiseEvent(Error, this, new ErrorArgs(-1, "Could not connect to server.")); return; } } _lastHeartBeat = DateTime.Now; _subSocket.Connect(string.Format("tcp://{0}:{1}", _host, _realTimePublishPort)); _dealerSocket.Connect(string.Format("tcp://{0}:{1}", _host, _historicalDataPort)); _running = true; //this loop sends out historical data requests and receives the data _dealerLoopThread = new Thread(DealerLoop) { Name = "Client Dealer Loop" }; _dealerLoopThread.Start(); //this loop takes care of replies to the request socket: heartbeats and data request status messages _poller = new Poller(); _poller.AddSocket(_reqSocket); _poller.AddSocket(_subSocket); _poller.AddSocket(_dealerSocket); Task.Factory.StartNew(_poller.Start, TaskCreationOptions.LongRunning); _heartBeatTimer = new Timer(1000); _heartBeatTimer.Elapsed += _timer_Elapsed; _heartBeatTimer.Start(); }
public void Connect(Guid from, string endpoint) { if (_connected) { throw new InvalidOperationException("Already connected"); } // Set our own identity on the socket so that receiving node // knows who each message came from. Note that we cannot use // the UUID directly as the identity since it may contain a // zero byte at the start, which libzmq does not like for // historical and arguably bogus reasons that it nonetheless // enforces. var identity = new byte[ZreConstants.ZreUuidLength]; identity[0] = 1; Array.Copy(from.ToByteArray(), 0, identity, 1, 16); _mailbox = _context.CreateDealerSocket(); _mailbox.Options.Identity = identity; // Set a high-water mark that allows for reasonable activity _mailbox.Options.ReceiveHighWatermark = ZreConstants.PeerExpired * 100; _mailbox.Options.SendHighWatermark = ZreConstants.PeerExpired * 100; try { _mailbox.Connect(endpoint); _endpoint = endpoint; _connected = true; _ready = false; } catch (Exception) { Trace.WriteLine( string.Format( "({0}) cannot connect to endpoint {1}", _origin, endpoint)); } if (_verbose) { Trace.WriteLine( string.Format( "({0}) connected to peer: endpoint {1}", _origin, endpoint)); } }
public Client(string address) { client = new DealerSocket(); client.Connect(address); }