public void AllEvents() { using (var context = new ZContext()) { using (var socket = ZSocket.Create(context, ZSocketType.PAIR)) { Assert.IsTrue(socket.Monitor(MonitorSocket)); using (var monitor = ZMonitor.Create(context, MonitorSocket)) { var events = new ConcurrentQueue <Tuple <object, ZMonitorEventArgs> >(); monitor.AllEvents += (sender, args) => events.Enqueue(Tuple.Create(sender, args)); monitor.Start(); using (var socket2 = ZSocket.Create(context, ZSocketType.PAIR)) { socket2.Bind("inproc://foo"); socket.Connect("inproc://foo"); socket.Close(); } Assert.That(() => events.Count >= 1, Is.True.After(1).Minutes.PollEvery(100).MilliSeconds); // TODO: the following is necessary since Dispose is not properly implemented monitor.Close(); monitor.Join(); // TODO: assert that the appropriate event(s) are received CollectionAssert.IsNotEmpty(events); } } } }
protected MonitoredSocketUser(String monitorAddress, ZSocketType socketType, TimeSpan pollWaitTime) { m_context = new ZContext(); m_socket = new ZSocket(m_context, socketType) { Linger = ZMQLinger, ReceiveHighWatermark = RCVHWM, SendHighWatermark = SNDHWM }; m_socket.Monitor(monitorAddress); m_monitor = ZMonitor.Create(m_context, monitorAddress); m_poller = ZPollItem.CreateReceiver(); m_monitor.AllEvents += (sender, e) => ScreenLogger.Log( ((Int32)e.Event.Event is 4096) ? $"Event fired on socket {e.Event.Address}: Handshake Success" : $"Event fired on socket {e.Event.Address}: {e.Event.Event}", LogObject.EventManager); m_cancelCondition = true; m_receiveBuffer = new BufferBlock <ZMessage>(); m_sendAction = new ActionBlock <ZMessage>((msg) => { m_socket.Send(msg); msg.Dispose(); }); m_pollWaitTime = MinPollWaitTime; if (pollWaitTime > m_pollWaitTime) { m_pollWaitTime = pollWaitTime; } ListenLoop(); }
public void Create() { using (var context = new ZContext()) { using (var monitor = ZMonitor.Create(context, MonitorSocket)) { } } }
protected MonitoredDoubleSocketUser(String tcpMonitorAddress, String udpMonitorAddress, ZSocketType socketType, TimeSpan pollWaitTime) { m_context = new ZContext(); m_tcpSocket = new ZSocket(m_context, socketType) { Linger = ZMQLinger, ReceiveHighWatermark = RCVHWM, SendHighWatermark = SNDHWM }; m_tcpSocket.Monitor(tcpMonitorAddress); m_tcpSocketMonitor = ZMonitor.Create(m_context, tcpMonitorAddress); m_poller = ZPollItem.CreateReceiver(); m_tcpSocketMonitor.AllEvents += (sender, e) => ScreenLogger.Log( ((Int32)e.Event.Event is 4096) ? $"Event fired on main TCP socket: Handshake Success" : $"Event fired on main TCP socket: {e.Event.Event}", LogObject.EventManager); /* * m_udpSocket = new ZSocket(m_context, socketType) * { * Linger = ZMQLinger, * ReceiveHighWatermark = RCVHWM, * SendHighWatermark = SNDHWM * }; * m_udpSocket.Monitor(udpMonitorAddress); * m_udpSocketMonitor = ZMonitor.Create(m_context, udpMonitorAddress); * m_poller = ZPollItem.CreateReceiver(); * m_udpSocketMonitor.AllEvents += (sender, e) => * ScreenLogger.Log( * ((Int32)e.Event.Event is 4096) ? * $"Event fired on main UDP socket: Handshake Success" : * $"Event fired on main UDP socket: {e.Event.Event}", * LogObject.EventManager); */ m_cancelConddition = true; m_receiveBuffer = new BufferBlock <(TransportProtocol, ZMessage)>(); m_tcpSocketSendAction = new ActionBlock <ZMessage>((msg) => { m_tcpSocket.Send(msg); msg.Dispose(); }); //m_udpSocketSendAction = new ActionBlock<ZMessage>((msg) => { m_udpSocket.Send(msg); msg.Dispose(); }); m_pollWaitTime = MinPollWaitTime; if (pollWaitTime > m_pollWaitTime) { m_pollWaitTime = pollWaitTime; } ListenLoop(); }
public void Create_Fails() { using (var context = new ZContext()) { context.MaxSockets = 1; using (var socket = ZSocket.Create(context, ZSocketType.PAIR)) { var exc = Assert.Throws <ZException>(() => ZMonitor.Create(context, MonitorSocket)); Assert.AreEqual(ZError.EMFILE, exc.Error); } } }
public void Start() { using (var context = new ZContext()) { using (var monitor = ZMonitor.Create(context, MonitorSocket)) { monitor.Start(); // TODO: the following is necessary since Dispose is not properly implemented monitor.Close(); monitor.Join(); } } }
static void Main(string[] args) { config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .AddEnvironmentVariables() .AddCommandLine(args) .Build(); KeyVaultClient keyVaultClient = new KeyVaultClient(GetAccessToken); var secret = keyVaultClient.GetSecretAsync(config["KeyVault:Url"], "ConnectionString", "650884c5bcd3425a9b74a27e1f55a603").GetAwaiter().GetResult(); Console.WriteLine($"The super secret connection string is: {secret.Value}"); MainAsync(args).GetAwaiter().GetResult(); Console.ReadKey(); string endpoint; using (var context = new ZContext()) using (var requester = new ZSocket(context, ZSocketType.REQ)) { // Connect requester.Connect(endpoint); var mon = ZMonitor.Create(context, endpoint2); mon.Start() for (int n = 0; n < 10; ++n) { string requestText = "Hello"; Console.Write("Sending {0}…", requestText); // Send requester.Send(new ZFrame(requestText)); // Receive using (ZFrame reply = requester.ReceiveFrame()) { Console.WriteLine(" Received: {0} {1}!", requestText, reply.ReadString()); } } } }
public void StopMonitor_ViaContextClose() { ZMonitor monitor; using (var context = new ZContext()) { using (var socket = ZSocket.Create(context, ZSocketType.PAIR)) { Assert.IsTrue(socket.Monitor(MonitorSocket)); monitor = ZMonitor.Create(context, MonitorSocket); { Assert.AreEqual(MonitorSocket, monitor.Endpoint); monitor.Start(); } } } monitor.Join(); }
public void Endpoint() { using (var context = new ZContext()) { using (var socket = ZSocket.Create(context, ZSocketType.PAIR)) { Assert.IsTrue(socket.Monitor(MonitorSocket)); using (var monitor = ZMonitor.Create(context, MonitorSocket)) { Assert.AreEqual(MonitorSocket, monitor.Endpoint); // TODO the following is necessary because ZMonitor.Dispose is not implemented properly monitor.Start(); // TODO: the following is necessary because ZMonitor.Dispose is not implemented properly monitor.Close(); monitor.Join(); } } } }
public static void PushPullDevice(IDictionary <string, string> dict, string[] args) { int who = dict.ContainsKey("--server") ? 1 : (dict.ContainsKey("--client") ? 2 : 0); bool doMonitor = dict.ContainsKey("--monitor"); if (args == null || args.Length < 1) { // say here were some arguments... args = new string[] { "World" }; } // Setup the ZContext context = ZContext.Create(); // We may have a cancellor and a pullDealer CancellationTokenSource cancellor0 = null; PushPullDevice pullDealer = null; var cancellor1 = doMonitor ? new CancellationTokenSource() : null; if (who == 0 || who == 1) { // Create the "Server" cancellor cancellor0 = new CancellationTokenSource(); // Setup the Dealer pullDealer = new PushPullDevice(context, Frontend, Backend); pullDealer.Start(cancellor0); pullDealer.Join(64); int i = -1; foreach (string name in args) { int j = ++i; // Create a Server var serverThread = new Thread(() => PushPullDevice_Server(cancellor0.Token, j, name, doMonitor)); serverThread.Start(); serverThread.Join(64); if (doMonitor) { var monitor = ZMonitor.Create(context, "inproc://PushPullDevice-Server" + j); monitor.AllEvents += (sender, e) => { Console.Write(" {0}: {1}", name, Enum.GetName(typeof(ZMonitorEvents), e.Event.Event)); if (e.Event.EventValue > 0) { Console.Write(" ({0})", e.Event.EventValue); } Console.WriteLine(); }; monitor.Start(cancellor1); monitor.Join(64); } } } if (who == 1) { Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { Console.WriteLine("Cancelled..."); if (cancellor1 != null) { // Cancel the Server cancellor1.Cancel(); } if (cancellor0 != null) { // Cancel the Server cancellor0.Cancel(); } if (pullDealer != null) { // Cancel the Device pullDealer.Stop(); } }; Console.WriteLine("Running..."); while (true) { Thread.Sleep(64); } } if (who == 0 || who == 2) { int i = -1; foreach (string arg in args) { int j = ++i; // foreach arg we are the Client, asking the Server if (doMonitor) { var monitor = ZMonitor.Create(context, "inproc://PushPullDevice-Client" + j); monitor.AllEvents += (sender, e) => { Console.Write(" {0}: {1}", arg, Enum.GetName(typeof(ZMonitorEvents), e.Event.Event)); if (e.Event.EventValue > 0) { Console.Write(" ({0})", e.Event.EventValue); } Console.WriteLine(); }; PushPullDevice_Client(j, arg, () => { monitor.Start(cancellor1); monitor.Join(64); }); } else { PushPullDevice_Client(j, arg); } } Thread.Sleep(250); } if (cancellor1 != null) { // Cancel the Monitor cancellor1.Cancel(); } if (cancellor0 != null) { // Cancel the Server cancellor0.Cancel(); } if (pullDealer != null) { // Cancel the Device pullDealer.Stop(); } // we could have done here context.Terminate() }
public static void StreamDealer(IDictionary <string, string> dict, string[] args) { int who = dict.ContainsKey("--server") ? 1 : (dict.ContainsKey("--client") ? 2 : 0); bool doMonitor = dict.ContainsKey("--monitor"); if (args == null || args.Length < 1) { // say here were some arguments... args = new string[] { "World" }; } if (!dict.ContainsKey("--frontend")) { Frontend = string.Format("tcp://{0}:8080", GetPublicIPs().FirstOrDefault()); } // Setup the ZContext context = ZContext.Create(); var cancellor0 = new CancellationTokenSource(); var streamDealer = new StreamDealerDevice(context, Frontend, Backend); streamDealer.Start(cancellor0); streamDealer.Join(64); var cancellor1 = doMonitor ? new CancellationTokenSource() : null; int i = -1; foreach (string arg in args) { int j = ++i; var serverThread = new Thread(() => StreamDealer_Server(cancellor0.Token, j, arg, doMonitor)); serverThread.Start(); serverThread.Join(64); if (doMonitor) { var monitor = ZMonitor.Create(context, "inproc://StreamDealer-Server" + j); monitor.AllEvents += (sender, e) => { Console.Write(" {0}: {1}", arg, Enum.GetName(typeof(ZMonitorEvents), e.Event.Event)); if (e.Event.EventValue > 0) { Console.Write(" ({0})", e.Event.EventValue); } if (!string.IsNullOrEmpty(e.Event.Address)) { Console.Write(" ({0})", e.Event.Address); } Console.WriteLine(); }; monitor.Start(cancellor1); monitor.Join(64); } } Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { Console.WriteLine("Cancelled..."); if (cancellor1 != null) { // Cancel the Monitor cancellor1.Cancel(); } if (cancellor0 != null) { // Cancel the Server cancellor0.Cancel(); } if (streamDealer != null) { streamDealer.Stop(); } // we could have done here context.Terminate() }; Console.WriteLine("Running..."); Console.WriteLine("Please start your browser on {0} ...", Frontend); while (true) { Thread.Sleep(250); } }
public static void Broker(ZContext context, string brokerAddrRequest, string brokerAddrResponse, string brokerAddrRequestPush, string brokerAddrResponsePull, string brokerAddrRequestPub, string brokerAddrResponseSub, string AddrToBroker1, string AddrToBroker2, string AddrFromBrokers, string brokerIdentity) { List <ArrayList> requestEndpoints = new List <ArrayList>(); List <ArrayList> responseEndpoints = new List <ArrayList>(); List <ArrayList> copies = new List <ArrayList>(); using (var brokerRequest = new ZSocket(context, ZSocketType.ROUTER)) using (var brokerResponse = new ZSocket(context, ZSocketType.DEALER)) using (var brokerRequestPush = new ZSocket(context, ZSocketType.PULL)) using (var brokerResponsePull = new ZSocket(context, ZSocketType.PUSH)) using (var brokerRequestPub = new ZSocket(context, ZSocketType.SUB)) using (var brokerResponseSub = new ZSocket(context, ZSocketType.PUB)) using (var brokerToOtherBroker1 = new ZSocket(context, ZSocketType.DEALER)) using (var brokerToOtherBroker2 = new ZSocket(context, ZSocketType.DEALER)) using (var brokerFromBrokers = new ZSocket(context, ZSocketType.DEALER)) { brokerRequestPub.SubscribeAll(); String reqMonitorAddr = "inproc://req." + brokerIdentity; brokerRequest.Monitor(reqMonitorAddr); ZMonitor reqMonitor = ZMonitor.Create(context, reqMonitorAddr); reqMonitor.Start(); bool reqConnected = false; bool reqDisconnected = false; reqMonitor.Disconnected += (s, a) => { reqDisconnected = true; reqConnected = false; }; reqMonitor.Accepted += (s, a) => { reqConnected = true; reqDisconnected = false; }; String subMonitorAddr = "inproc://sub." + brokerIdentity; brokerResponseSub.Monitor(subMonitorAddr); ZMonitor subMonitor = ZMonitor.Create(context, subMonitorAddr); subMonitor.Start(); bool subConnected = false; bool subDisconnected = false; subMonitor.Disconnected += (s, a) => { subDisconnected = true; subConnected = false; }; subMonitor.Accepted += (s, a) => { subConnected = true; }; String pullMonitorAddr = "inproc://pull." + brokerIdentity; brokerResponsePull.Monitor(pullMonitorAddr); ZMonitor pullMonitor = ZMonitor.Create(context, pullMonitorAddr); pullMonitor.Start(); bool pullConnected = false; bool pullDisconnected = false; pullMonitor.Disconnected += (s, a) => { pullDisconnected = true; pullConnected = false; }; pullMonitor.Accepted += (s, a) => { pullConnected = true; }; brokerRequest.Bind(brokerAddrRequest); brokerResponse.Bind(brokerAddrResponse); brokerFromBrokers.Bind(AddrFromBrokers); brokerToOtherBroker1.Connect(AddrToBroker1); brokerToOtherBroker2.Connect(AddrToBroker2); brokerRequestPush.Bind(brokerAddrRequestPush); brokerResponsePull.Bind(brokerAddrResponsePull); brokerRequestPub.Bind(brokerAddrRequestPub); brokerResponseSub.Bind(brokerAddrResponseSub); ZError error; ZMessage request; ZPollItem poll = ZPollItem.CreateReceiver(); string fileRequest = "Request.txt"; string fileResponse = "Response.txt"; //string pathReq =".\\Request\\" + uid + ".txt"; //string pathRep = ".\\Request\\" + uid + ".txt"; Directory.CreateDirectory("Request"); Directory.CreateDirectory("Response"); if (!File.Exists(fileRequest)) { File.Create(fileRequest).Close(); } if (!File.Exists(fileResponse)) { File.Create(fileResponse).Close(); } while (true) { SendCopies(copies, brokerIdentity); if (requestEndpoints.Any()) { for (int i = 0; i < requestEndpoints.Count; i++) { string content = requestEndpoints[i][0].ToString(); string uid = requestEndpoints[i][1].ToString(); if (requestEndpoints[i].Count > 5) { string addrOrTopic; if (requestEndpoints[i][5].ToString().Length == 20) { addrOrTopic = requestEndpoints[i][5].ToString().Substring(16, 4); } else { addrOrTopic = requestEndpoints[i][5].ToString(); } ZSocket socket = (ZSocket)requestEndpoints[i][3]; string address = socket.LastEndpoint.Substring(14, 4); bool sended = false; if (addrOrTopic == address) { if (socket.SocketType == ZSocketType.PUSH & pullDisconnected == false & pullConnected == true) { sended = Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), content, uid, "Server"); } else { sended = Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), content, uid, "Server"); } } else if (socket.SocketType == ZSocketType.PUB & subDisconnected == false & subConnected == true) { sended = Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), content, uid, "Server", addrOrTopic); } if (socket != brokerResponse && sended == true) { RemoveFromList(requestEndpoints, Guid.Parse(uid)); string messageType = "REP"; MoveFile(uid, content); //WriteToFile(fileResponse, Guid.Parse(uid)); DeleteFile(uid); UpdateFile(fileRequest, uid); AddToList(copies, content, Guid.Parse(uid), messageType, null, null, brokerToOtherBroker1, brokerToOtherBroker2); } } } } if (responseEndpoints.Any()) { for (int i = 0; i < responseEndpoints.Count; i++) { string content = responseEndpoints[i][0].ToString(); string uid = responseEndpoints[i][1].ToString(); if (responseEndpoints[i].Count > 4) { string identity = responseEndpoints[i][2].ToString(); ZSocket socket = (ZSocket)responseEndpoints[i][3]; string address = responseEndpoints[i][4].ToString().Substring(14, 4); string address2 = brokerRequest.LastEndpoint.Substring(14, 4); if (address == address2) { if (reqDisconnected == true & reqConnected == false) { Thread.Sleep(5 * 1000); } if (reqDisconnected == false & reqConnected == true) { Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), content, uid, identity); DeleteFile(uid); UpdateFile(fileResponse, uid); RemoveFromList(responseEndpoints, Guid.Parse(uid)); string messageType = "CON"; AddToList(copies, content, Guid.Parse(uid), messageType, null, null, brokerToOtherBroker1, brokerToOtherBroker2); } } } } } if (brokerRequest.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(1))) { string receiverAddress = request[2].ReadString(); string identity = request[3].ReadString(); string content = request[4].ReadString(); string messageType = "REQ"; string senderAddress = brokerRequest.LastEndpoint.Substring(0, brokerRequest.LastEndpoint.Length - 1); Guid guid = Guid.NewGuid(); Console.WriteLine("{0} <- {1} : [{2} {3}]", brokerIdentity, identity, messageType, guid.ToString()); CreateFile(guid, content); WriteToFile(fileRequest, guid); AddToList(requestEndpoints, content, guid, identity, senderAddress, receiverAddress, brokerResponse); AddToList(copies, content, guid, messageType, senderAddress, receiverAddress, brokerToOtherBroker1, brokerToOtherBroker2); } else { ErrorChecker(error); } if (brokerRequestPush.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(1))) { string receiverAddress = request[0].ReadString(); string identity = request[1].ReadString(); string content = request[2].ReadString(); string messageType = "REQ"; string senderAddress = brokerRequestPush.LastEndpoint.Substring(0, brokerRequest.LastEndpoint.Length - 1); Guid guid = Guid.NewGuid(); Console.WriteLine("{0} <- {1} : [{2}]", brokerIdentity, identity, guid.ToString()); CreateFile(guid, content); WriteToFile(fileRequest, guid); AddToList(requestEndpoints, content, guid, identity, senderAddress, receiverAddress, brokerResponsePull); AddToList(copies, content, guid, messageType, senderAddress, receiverAddress, brokerToOtherBroker1, brokerToOtherBroker2); } else { ErrorChecker(error); } if (brokerRequestPub.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(1))) { string topic = request[0].ReadString(); string identity = request[1].ReadString(); string content = request[2].ReadString(); string messageType = "REQ"; string senderAddress = brokerRequestPub.LastEndpoint.Substring(0, brokerRequest.LastEndpoint.Length - 1); Guid guid = Guid.NewGuid(); Console.WriteLine("{0} <- {1} : [{2}]", brokerIdentity, identity, guid.ToString()); CreateFile(guid, content, topic); WriteToFile(fileRequest, guid); AddToList(requestEndpoints, content, guid, identity, senderAddress, topic, brokerResponseSub); AddToList(copies, content, guid, messageType, senderAddress, topic, brokerToOtherBroker1, brokerToOtherBroker2); } else { ErrorChecker(error); } int counter = 1; do { if (brokerFromBrokers.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(100))) { string identity = request[0].ReadString(); string content = request[1].ReadString(); string uid = request[2].ReadString(); string messageType = request[3].ReadString(); string senderAddress = null; string receiverAddress = null; if (request.Count > 5) { senderAddress = request[4].ReadString(); receiverAddress = request[5].ReadString(); } else if (request.Count > 4) { senderAddress = request[4].ReadString(); } ZSocket socket2 = null; ZSocket socket = null; if ((brokerIdentity == "Broker1" & identity == "Broker2") || (brokerIdentity == "Broker2" & identity == "Broker1") || (brokerIdentity == "Broker3" & identity == "Broker1")) { socket = brokerToOtherBroker1; } else if ((brokerIdentity == "Broker1" & identity == "Broker3") || (brokerIdentity == "Broker2" & identity == "Broker3") || (brokerIdentity == "Broker3" & identity == "Broker2")) { socket = brokerToOtherBroker2; } if (messageType == "CONCOP") { RemoveFromList(copies, Guid.Parse(uid), content, socket); } else { if (messageType == "REQ") { if (AddressforClientReq.Contains(senderAddress)) { socket2 = brokerResponse; } else if (AddressforClientPush.Contains(senderAddress)) { socket2 = brokerResponsePull; } else if (AddressforClientPub.Contains(senderAddress)) { socket2 = brokerResponseSub; } AddToList(requestEndpoints, content, Guid.Parse(uid), identity, senderAddress, receiverAddress, socket2); } else if (messageType == "REP") { if (AddressforClientReq.Contains(senderAddress)) { var list = GetFromList(requestEndpoints, Guid.Parse(uid)); if (list != null) { string identity2 = list[2].ToString(); AddToList(responseEndpoints, content, Guid.Parse(uid), identity2, senderAddress, null, brokerRequest); } } RemoveFromList(requestEndpoints, Guid.Parse(uid)); } else if (messageType == "CON") { RemoveFromList(responseEndpoints, Guid.Parse(uid)); } Send(socket, Encoding.UTF8.GetBytes(brokerIdentity), messageType, uid, "CONCOP", null, null); } } else { ErrorChecker(error); } counter++; }while (copies.Any() & counter < 4); if (brokerResponse.PollIn(poll, out request, out error, TimeSpan.FromMilliseconds(1))) { string uid = request[2].ReadString(); string identity = request[3].ReadString(); string content = request[4].ReadString(); string messageType = "REP"; ArrayList list = GetFromList(requestEndpoints, Guid.Parse(uid)); string address = list[4].ToString(); string identity2 = list[2].ToString(); Console.WriteLine("{0} <- {1} : [{2} {3}]", brokerIdentity, identity, uid, messageType); MoveFile(uid, content); WriteToFile(fileResponse, Guid.Parse(uid)); UpdateFile(fileRequest, uid); RemoveFromList(requestEndpoints, Guid.Parse(uid)); AddToList(responseEndpoints, content, Guid.Parse(uid), identity2, address, null, brokerRequest); AddToList(copies, content, Guid.Parse(uid), messageType, address, null, brokerToOtherBroker1, brokerToOtherBroker2); } else { ErrorChecker(error); } } } }