internal NmqMessageSender(Uri serviceUri) { context = NetMQContext.Create(); socket = context.CreateRequestSocket(); var address = string.Format("tcp://{0}:{1}", serviceUri.Host, serviceUri.Port); socket.Connect(address); }
public void Start () { ThrowIfDisposed (); nmqPoller = new Poller (); nmqClient = nmqContext.CreateRequestSocket (); nmqClient.Connect (Address.AbsoluteUri.TrimEnd ('/')); nmqScheduler = new NetMQScheduler (nmqContext, nmqPoller); Task.Factory.StartNew (() => nmqPoller.Start (), TaskCreationOptions.LongRunning); }
public void Start() { poller = new Poller(); clientSocket = context.CreateDealerSocket(); clientSocket.ReceiveReady += clientSocket_ReceiveReady; clientSocket.Connect(address); scheduler = new NetMQScheduler(context, poller); Task.Factory.StartNew(poller.Start, TaskCreationOptions.LongRunning); }
public MessageHelper(string address, string topic) { _context = NetMQContext.Create(); _subscribeSocket = _context.CreateSubscriberSocket(); _subscribeSocket.Connect(address); _subscribeSocket.ReceiveReady += SubscribeSocketOnReceiveReady; _subscribeSocket.Subscribe(topic); _poller = new Poller(); _poller.AddSocket(_subscribeSocket); Task.Factory.StartNew(_poller.Start); }
public TestReciever Start() { _context = NetMQContext.Create(); _socket = _context.CreatePullSocket(); _socket.Connect(_publisherAddress); Task.Run(() => { Recieve(); }); return this; }
public Subscriber(params string[] messageKeys) { if (messageKeys != null && messageKeys.Length > 0) subscribeTo.AddRange(messageKeys.ToList()); context = NetMQContext.Create(); server = context.CreateSubscriberSocket(); server.Connect("tcp://127.0.0.1:5003"); subscribeTo.ForEach(server.Subscribe); Thread.Sleep(500); }
public string Request(string service, string msg, int timeoutmsec) { string resp = string.Empty; LinkAddress address = config.ReqRep.FindLinkAddress(service); if (address == null) { return(resp); } bool pollResult = false; string requestId = Guid.NewGuid().ToString(); using (NetMQContext context = NetMQContext.Create()) { NetMQSocket client = context.CreateRequestSocket(); client.Options.Linger = TimeSpan.Zero; client.Options.Identity = Encoding.UTF8.GetBytes(requestId); client.Connect(address.Address); try { byte[] data = Encoding.UTF8.GetBytes(msg); client.Send(data); } catch (Exception) { client.Disconnect(address.Address); client.Dispose(); return(resp); } client.ReceiveReady += ClientOnReceiveReady; pollResult = client.Poll(TimeSpan.FromMilliseconds(timeoutmsec)); client.ReceiveReady -= ClientOnReceiveReady; client.Disconnect(address.Address); client.Dispose(); } if (pollResult) { if (responseMsgs.ContainsKey(requestId)) { responseMsgs.TryRemove(requestId, out resp); } } return(resp); }
// initialized sprites void Start() { AsyncIO.ForceDotNet.Force(); calImages = new Sprite[10]; calImages[0] = Resources.Load <Sprite>("notargets"); calImages[1] = Resources.Load <Sprite>("targetTL"); calImages[2] = Resources.Load <Sprite>("targetTM"); calImages[3] = Resources.Load <Sprite>("targetTR"); calImages[4] = Resources.Load <Sprite>("targetML"); calImages[5] = Resources.Load <Sprite>("targetMM"); calImages[6] = Resources.Load <Sprite>("targetMR"); calImages[7] = Resources.Load <Sprite>("targetBL"); calImages[8] = Resources.Load <Sprite>("targetBM"); calImages[9] = Resources.Load <Sprite>("targetBR"); calCount = 0; curCount = 0; gameObject.GetComponent <Image> ().sprite = calImages [calCount]; //max coords 1180*564 transX = 0; transY = 0; targetPrefab = GameObject.FindGameObjectWithTag("RaycastTarget"); targetPrefab.SetActive(false); targetPrefab.layer = 2; //ignore raycast layer isVisible = false; AsyncIO.ForceDotNet.Force(); //setup sockets //hangs???? //http://forum.unity3d.com/threads/netmq-basic.298104/ //must compile myself //https://github.com/zeromq/netmq/issues/98 context = NetMQContext.Create(); server = context.CreatePublisherSocket(); server.Bind("tcp://127.0.0.1:5556"); client = context.CreateSubscriberSocket(); client.Connect("tcp://127.0.0.1:5556"); client.Subscribe("coord"); Debug.Log(System.Environment.Version); /*server.SendMore("coord").Send ("200 200"); * string top = client.ReceiveString (); * string message = client.ReceiveString (); * Debug.Log (message); * string[] coord = message.Split (); * transX = int.Parse (coord [0]); * transY = int.Parse (coord [1]);*/ }
internal static void Start(this NetMQSocket socket, string address, SocketType socketType) { switch (socketType) { case SocketType.Client: socket.Connect(address); break; case SocketType.Server: socket.Bind(address); break; default: throw new ArgumentException(string.Format("Unknown SocketType {0}", socketType), "socketType"); } }
protected override void StartMethod() { _zmqContext = NetMQContext.Create(); _zmqSocket = _zmqContext.CreateSubscriberSocket(); if (string.IsNullOrEmpty(_subsPrefix)) { _zmqSocket.Subscribe(string.Empty); } else { _zmqSocket.Subscribe(Encoding.UTF8.GetBytes(_subsPrefix)); } _zmqSocket.Connect(_endPoint); }
public void Ipv6ToIpv4() { using (var context = NetMQContext.Create()) using (var localDealer = context.CreateDealerSocket()) using (NetMQSocket connectingDealer = context.CreateDealerSocket()) { localDealer.Options.IPv4Only = false; var port = localDealer.BindRandomPort(string.Format("tcp://*")); connectingDealer.Connect(string.Format("tcp://{0}:{1}", IPAddress.Loopback, port)); connectingDealer.SendFrame("test"); Assert.AreEqual("test", localDealer.ReceiveFrameString()); } }
// initialized sprites void Start() { AsyncIO.ForceDotNet.Force(); calImages = new Sprite[10]; calImages[0] = Resources.Load<Sprite>("notargets"); calImages[1] = Resources.Load<Sprite>("targetTL"); calImages[2] = Resources.Load<Sprite>("targetTM"); calImages[3] = Resources.Load<Sprite>("targetTR"); calImages[4] = Resources.Load<Sprite>("targetML"); calImages[5] = Resources.Load<Sprite>("targetMM"); calImages[6] = Resources.Load<Sprite>("targetMR"); calImages[7] = Resources.Load<Sprite>("targetBL"); calImages[8] = Resources.Load<Sprite>("targetBM"); calImages[9] = Resources.Load<Sprite>("targetBR"); calCount = 0; curCount = 0; gameObject.GetComponent<Image> ().sprite = calImages [calCount]; //max coords 1180*564 transX = 0; transY = 0; targetPrefab = GameObject.FindGameObjectWithTag ("RaycastTarget"); targetPrefab.SetActive (false); targetPrefab.layer = 2;//ignore raycast layer isVisible = false; AsyncIO.ForceDotNet.Force(); //setup sockets //hangs???? //http://forum.unity3d.com/threads/netmq-basic.298104/ //must compile myself //https://github.com/zeromq/netmq/issues/98 context = NetMQContext.Create (); server = context.CreatePublisherSocket (); server.Bind("tcp://127.0.0.1:5556"); client = context.CreateSubscriberSocket (); client.Connect("tcp://127.0.0.1:5556"); client.Subscribe ("coord"); Debug.Log (System.Environment.Version); /*server.SendMore("coord").Send ("200 200"); string top = client.ReceiveString (); string message = client.ReceiveString (); Debug.Log (message); string[] coord = message.Split (); transX = int.Parse (coord [0]); transY = int.Parse (coord [1]);*/ }
//? swtich to ctor with Socket and Sender? move setup to factory? public SendSocket(NetMQContext context, string address, Func <T, byte[]> marshaller, ZmqSocketType type = ZmqSocketType.Pub, bool bind = true) { _msgSender = marshaller; _socket = context.CreateSocket(type); if (bind) { _socket.Bind(address); } else { _socket.Connect(address); } }
private static bool TryRequest(NetMQContext context, string endpoint, string requestString) { Console.WriteLine("Trying echo service at {0}", endpoint); NetMQSocket client = context.CreateRequestSocket(); client.Options.Linger = TimeSpan.Zero; client.Connect(endpoint); client.Send(requestString); client.ReceiveReady += ClientOnReceiveReady; bool pollResult = client.Poll(TimeSpan.FromMilliseconds(REQUEST_TIMEOUT)); client.ReceiveReady -= ClientOnReceiveReady; client.Disconnect(endpoint); client.Dispose(); return(pollResult); }
public void Issue52_ReqToRouterBug() { using (var ctx = NetMQContext.Create()) { using (NetMQSocket router = ctx.CreateRouterSocket(), req = ctx.CreateRequestSocket()) { router.Bind("inproc://example"); req.Connect("inproc://example"); string testmessage = "Simple Messaging Test"; req.Send(testmessage); var msg = router.ReceiveMessage(); Assert.AreEqual(3, msg.FrameCount); Assert.AreEqual(msg[2].ConvertToString(), testmessage); } } }
public void runClient() { NetMQContext context = NetMQContext.Create(); NetMQSocket client = context.CreateResponseSocket(); client.Connect("tcp://localhost:5555"); NetMQMessage message = new NetMQMessage(); NetMQMessage message2 = new NetMQMessage(); while (true) { message = client.ReceiveMessage(false); message2.Append(message.Pop().ConvertToString() + "Tobi"); message2.Append(message.Pop().ConvertToInt32() + 12); client.SendMessage(message2, false); System.Threading.Thread.Sleep(100); } }
private void SendEvents(String submissionUri, CancellationToken cancellationToken) { using (NetMQContext context = NetMQContext.Create()) { using (NetMQSocket pushSocket = context.CreatePushSocket()) { pushSocket.IgnoreErrors = true; pushSocket.Connect(submissionUri); Logger.Info("ZeroMQCache: Connected to submissionUri \"{0}\".", submissionUri); while (!cancellationToken.IsCancellationRequested) { try { ZeroMQMessage message; if (mQueue.TryTake(out message, TimeSpan.FromSeconds(1))) { Logger.Debug("ZeroMQCache: Sending -> {0}", message.ToString()); pushSocket.SendMore(message.Topic); pushSocket.SendMore(message.Client); pushSocket.Send(message.Content); } } catch (OperationCanceledException) { // We have been asked to cancel operation break; } catch (Exception ex) { Logger.Error("ZeroMQCache: Error sending message.", ex); } } // Close socket pushSocket.Close(); } context.Terminate(); } }
public void BindRandom() { using (NetMQContext context = NetMQContext.Create()) { using (NetMQSocket randomDealer = context.CreateDealerSocket()) { int port = randomDealer.BindRandomPort("tcp://*"); using (NetMQSocket connectingDealer = context.CreateDealerSocket()) { connectingDealer.Connect("tcp://127.0.0.1:" + port); randomDealer.Send("test"); Assert.AreEqual("test", connectingDealer.ReceiveString()); } } } }
public void Ipv6ToIpv4() { using (NetMQContext context = NetMQContext.Create()) { using (NetMQSocket localDealer = context.CreateDealerSocket()) { localDealer.Options.IPv4Only = false; localDealer.Bind(string.Format("tcp://*:5002")); using (NetMQSocket connectingDealer = context.CreateDealerSocket()) { connectingDealer.Connect("tcp://" + IPAddress.Loopback.ToString() + ":5002"); connectingDealer.Send("test"); Assert.AreEqual("test", localDealer.ReceiveString()); } } } }
public bool TryConnectAndMonitorSocket(NetMQSocket socket, string address, NetMQPoller poller = null, Action <IConnectionMonitor, bool> onConnectionStateChanged = null) { _onConnectionStateChanged = onConnectionStateChanged; _monitor = new NetMQMonitor(socket, $"inproc://monitor.socket/{Guid.NewGuid()}", SocketEvents.Connected | SocketEvents.Disconnected); _monitor.Connected += MonitorConnected; _monitor.Disconnected += MonitorDisconnected; if (poller == null) { _monitorTask = _monitor.StartAsync(); } else { _monitor.AttachToPoller(poller); } socket.Connect(address); return(WaitForConnection()); }
public NetMQScheduler(NetMQContext context, Poller poller = null) { m_context = context; if (poller == null) { m_ownPoller = true; m_poller = new Poller(); } else { m_ownPoller = false; m_poller = poller; } m_tasksQueue = new ConcurrentQueue<Task>(); m_syncObject = new object(); m_schedulerId = Interlocked.Increment(ref s_schedulerCounter); m_address = string.Format("{0}://scheduler-{1}", NetMQ.zmq.Address.InProcProtocol, m_schedulerId); m_serverSocket = context.CreatePullSocket(); m_serverSocket.Options.Linger = TimeSpan.Zero; m_serverSocket.Bind(m_address); m_currentMessageHandler = OnMessageFirstTime; m_serverSocket.ReceiveReady += m_currentMessageHandler; m_poller.AddSocket(m_serverSocket); m_clientSocket = m_context.CreatePushSocket(); m_clientSocket.Connect(m_address); m_schedulerThread = new ThreadLocal<bool>(() => false); if (m_ownPoller) { Task.Factory.StartNew(m_poller.Start, TaskCreationOptions.LongRunning); } }
public AsyncRequestSocket(NetMQContext context, string address, Func <TRequest, byte[]> requestMarshaller, Func <byte[], TReply> replyUnmarshaller, IFiber fiber) { _requestMarshaller = requestMarshaller; _replyUnmarshaller = replyUnmarshaller; _fiber = fiber; _internalChannel.SetRequestHandler(_fiber, OnRequest); _replyContext = context; int basePort = int.Parse(address.Split(':')[2]); _replySocket = _replyContext.CreateSocket(ZmqSocketType.Sub); _replySocket.Connect(address.Substring(0, address.LastIndexOf(":")) + ":" + (basePort + 1)); _replySocket.Subscribe(_id); _requestSocket = _replyContext.CreateSocket(ZmqSocketType.Push); _requestSocket.Connect(address); _fiber.Start(); Task.Factory.StartNew(Run, TaskCreationOptions.LongRunning); }
public void Start() { _worker.ReceiveReady += _worker_ReceiveReady; _worker.Connect("tcp://localhost:5556"); _heartbeatTimer = new NetMQTimer(Paranoid.HEARTBEAT_INTERVAL_MS); _heartbeatTimer.Elapsed += heartbeatTimer_Elapsed; _poller = new Poller(); _poller.AddSocket(_worker); _poller.AddTimer(_heartbeatTimer); _scheduler = new NetMQScheduler(_context, _poller); _nextHeartbeatAt = DateTime.Now.AddMilliseconds(Paranoid.HEARTBEAT_INTERVAL_MS); _cylces = 0; Task.Factory.StartNew(() => Run(), TaskCreationOptions.LongRunning); SendReady(); }
public void Start() { _context = NetMQContext.Create(); // Dealer can send any number of requests and just wait for the answers _socket = _context.CreateDealerSocket(); // REP can send only one request and wait reply for that before sending more //_socket = _context.CreateRequestSocket(); var clientId = Guid.NewGuid(); _socket.Options.Identity = Encoding.Unicode.GetBytes(clientId.ToString()); Console.WriteLine("Client: {0}", clientId.ToPrintable()); _socket.Connect(_endPoint); _socket.ReceiveReady += _socket_ReceiveReady; _poller = new Poller(); _poller.AddSocket(_socket); Task.Factory.StartNew(() => Run(), TaskCreationOptions.LongRunning); }
/// <summary> /// Create a new NetMQScheduler object within the given context, and optionally using the given poller. /// </summary> /// <param name="context">the NetMQContext to create this NetMQScheduler within</param> /// <param name="poller">(optional)the Poller for this Net to use</param> public NetMQScheduler([NotNull] NetMQContext context, [CanBeNull] Poller poller = null) { if (poller == null) { m_ownPoller = true; m_poller = new Poller(); } else { m_ownPoller = false; m_poller = poller; } m_tasksQueue = new ConcurrentQueue<Task>(); m_syncObject = new object(); var schedulerId = Interlocked.Increment(ref s_schedulerCounter); var address = string.Format("{0}://scheduler-{1}", Address.InProcProtocol, schedulerId); m_serverSocket = context.CreatePullSocket(); m_serverSocket.Options.Linger = TimeSpan.Zero; m_serverSocket.Bind(address); m_currentMessageHandler = OnMessageFirstTime; m_serverSocket.ReceiveReady += m_currentMessageHandler; m_poller.AddSocket(m_serverSocket); m_clientSocket = context.CreatePushSocket(); m_clientSocket.Connect(address); m_schedulerThread = new ThreadLocal<bool>(() => false); if (m_ownPoller) { m_poller.PollTillCancelledNonBlocking(); } }
public void MultipleLargeMessages() { byte[] largeMessage = new byte[12000]; for (int i = 0; i < 12000; i++) { largeMessage[i] = (byte)(i % 256); } using (NetMQContext context = NetMQContext.Create()) { using (NetMQSocket pubSocket = context.CreatePublisherSocket()) { pubSocket.Bind("tcp://127.0.0.1:5558"); using (NetMQSocket subSocket = context.CreateSubscriberSocket()) { subSocket.Connect("tcp://127.0.0.1:5558"); subSocket.Subscribe(""); Thread.Sleep(1000); pubSocket.Send(""); subSocket.Receive(); for (int i = 0; i < 100; i++) { pubSocket.Send(largeMessage); byte[] recvMesage = subSocket.Receive(); for (int j = 0; j < 12000; j++) { Assert.AreEqual(largeMessage[j], recvMesage[j]); } } } } } }
public void HasInTest() { using (NetMQContext context = NetMQContext.Create()) { using (NetMQSocket server = context.CreateRouterSocket()) { server.Bind("tcp://*:5557"); // no one sent a message so it should be fasle Assert.IsFalse(server.HasIn); using (NetMQSocket client = context.CreateDealerSocket()) { client.Connect("tcp://localhost:5557"); // wait for the client to connect Thread.Sleep(100); // now we have one client connected but didn't send a message yet Assert.IsFalse(server.HasIn); client.Send("1"); // wait for the message to arrive Thread.Sleep(100); // the has in should indicate a message is ready Assert.IsTrue(server.HasIn); byte[] identity = server.Receive(); string message = server.ReceiveString(); Assert.AreEqual(message, "1"); // we read the message, it should false again Assert.IsFalse(server.HasIn); } } } }
public void Connect() { if (_sub != null) { return; } _connectionLock.Wait(); try { if (_sub == null) { switch (_ZeroMQOptions.Pattern) { case NetMQPattern.PushPull: _sub = new PullSocket(); break; case NetMQPattern.PubSub: _sub = new SubscriberSocket(); break; default: break; } _sub.Connect(HostAddress); } } catch (Exception ex) { OnLog?.Invoke(this, new LogMessageEventArgs() { LogType = MqLogType.ExceptionReceived, Reason = $"{HostAddress }-{_queueName}-{ex.Message}" }); } finally { _connectionLock.Release(); } }
/// <summary> /// Add an instrument to QDMS. /// </summary> /// <param name="instrument"></param> /// <returns>The instrument with its ID set if successful, null otherwise.</returns> public Instrument AddInstrument(Instrument instrument) { if (!Connected) { RaiseEvent(Error, this, new ErrorArgs(-1, "Could not add instrument - not connected.")); return(null); } if (instrument == null) { RaiseEvent(Error, this, new ErrorArgs(-1, "Could not add instrument - instrument is null.")); return(null); } using (NetMQSocket s = _context.CreateSocket(ZmqSocketType.Req)) { s.Connect(string.Format("tcp://{0}:{1}", _host, _instrumentServerPort)); var ms = new MemoryStream(); s.SendMore("ADD"); //first we send an "ADD" request //then we need to serialize and send the instrument s.Send(MyUtils.ProtoBufSerialize(instrument, ms)); //then get the reply string result = s.ReceiveString(TimeSpan.FromSeconds(1)); if (result != "SUCCESS") { RaiseEvent(Error, this, new ErrorArgs(-1, "Instrument addition failed: received no reply.")); return(null); } //Addition was successful, receive the instrument and return it byte[] serializedInstrument = s.Receive(); return(MyUtils.ProtoBufDeserialize <Instrument>(serializedInstrument, ms)); } }
/// <summary> /// connects to the broker, if a socket already exists it will be disposed and /// a new socket created and connected /// MDP requires a REQUEST socket for a client /// </summary> /// <exception cref="ApplicationException">NetMQContext must not be <c>null</c></exception> /// <exception cref="ApplicationException">if broker address is empty or <c>null</c></exception> private void Connect() { if (!ReferenceEquals(m_client, null)) { m_client.Dispose(); } m_client = new RequestSocket(); if (m_identity != null) { m_client.Options.Identity = m_identity; } // attach the event handler for incoming messages m_client.ReceiveReady += ProcessReceiveReady; m_client.Connect(m_brokerAddress); m_connected = true; Log(string.Format("[CLIENT] connecting to broker at {0}", m_brokerAddress)); }
static void Client(NetMQContext context) { using (NetMQSocket clientSocket = context.CreateRequestSocket()) { clientSocket.Connect("tcp://127.0.0.1:5555"); while (true) { Console.WriteLine("Please enter your message:"); string message = Console.ReadLine(); clientSocket.SendFrame(message); string answer = clientSocket.ReceiveFrameString(); Console.WriteLine("Answer from server: {0}", answer); if (message == "exit") { break; } } } }
public void Start() { _zmqContext = NetMQContext.Create(); _zmqSocket = _zmqContext.CreateSubscriberSocket(); if (string.IsNullOrEmpty(_subsPrefix)) { _zmqSocket.Subscribe(string.Empty); } else { _zmqSocket.Subscribe(Encoding.UTF8.GetBytes(_subsPrefix)); } _zmqSocket.Connect(_endPoint); _zmqSocket.ReceiveReady += _zmqSocket_ReceiveReady; _poller = new Poller(); _poller.AddSocket(_zmqSocket); Task.Factory.StartNew(() => Run(), TaskCreationOptions.LongRunning); }
private NetMQScheduler(Poller poller, PushSocket pushSocket, PullSocket pullSocket) { if (poller == null) { m_ownPoller = true; m_poller = new Poller(); } else { m_ownPoller = false; m_poller = poller; } var address = string.Format("{0}://scheduler-{1}", Address.InProcProtocol, Interlocked.Increment(ref s_schedulerCounter)); m_serverSocket = pullSocket; m_serverSocket.Options.Linger = TimeSpan.Zero; m_serverSocket.Bind(address); m_currentMessageHandler = OnMessageFirstTime; m_serverSocket.ReceiveReady += m_currentMessageHandler; m_poller.AddSocket(m_serverSocket); m_clientSocket = pushSocket; m_clientSocket.Connect(address); m_isSchedulerThread = new ThreadLocal<bool>(() => false); if (m_ownPoller) { m_poller.PollTillCancelledNonBlocking(); } }
static void Main(string[] args) { using (var context = NetMQContext.Create()) { worker = context.CreateRequestSocket(); var randomizer = new Random(DateTime.Now.Millisecond); Guid guid = Guid.NewGuid(); worker.Options.Identity = Encoding.Unicode.GetBytes(guid.ToString()); worker.ReceiveReady += WorkerOnReceiveReady; worker.Connect(SERVER_ENDPOINT); Console.WriteLine("W: {0} worker ready", guid); worker.Send(Encoding.Unicode.GetBytes(LRU_READY)); var cycles = 0; while (true) { cycles += 1; if (cycles > 3 && randomizer.Next(0, 5) == 0) { Console.WriteLine("W: {0} simulating a crash", guid); System.Threading.Thread.Sleep(5000); //break; } else if (cycles > 3 && randomizer.Next(0, 5) == 0) { Console.WriteLine("W: {0} simulating CPU overload", guid); System.Threading.Thread.Sleep(3000); } Console.WriteLine("W: {0} normal reply", guid); worker.Poll(TimeSpan.FromMilliseconds(1000)); } } }
/// <summary> /// connects to the broker, if a socket already exists it will be disposed and /// a new socket created and connected (Linger is set to 1) /// The Client connects to broker using a DEALER socket /// </summary> private void Connect() { if (!ReferenceEquals(m_client, null)) { m_poller.Remove(m_client); m_client.Dispose(); } m_client = new DealerSocket(); // sets a low linger to avoid port exhaustion, messages can be lost since it'll be sent again m_client.Options.Linger = m_lingerTime; if (m_identity != null) m_client.Options.Identity = m_identity; // set timeout timer to reconnect if no message is received during timeout m_timer.EnableAndReset(); // attach the event handler for incoming messages m_client.ReceiveReady += OnProcessReceiveReady; m_poller.Add(m_client); // TODO Define HighWaterMark!? m_client.Connect(m_brokerAddress); m_connected = true; Log($"[CLIENT] connecting to broker at {m_brokerAddress}"); }
public void Connect(string address) { Socket.Connect(address); EndPoints.Add(address); }
public void ConnectOrBindAddress(NetMQSocket socket) { var address = $"{Uri.Scheme}://{Uri.Host}:{Uri.Port}"; socket.Connect(address); }
/// <summary> /// Query the server for contracts matching a particular set of features. /// </summary> /// <param name="instrument">An Instrument object; any features that are not null will be search parameters. If null, all instruments are returned.</param> /// <returns>A list of instruments matching these features.</returns> public List <Instrument> FindInstruments(Instrument instrument = null) { if (!Connected) { RaiseEvent(Error, this, new ErrorArgs(-1, "Could not request instruments - not connected.")); return(new List <Instrument>()); } using (NetMQSocket s = _context.CreateSocket(ZmqSocketType.Req)) { s.Connect(string.Format("tcp://{0}:{1}", _host, _instrumentServerPort)); var ms = new MemoryStream(); if (instrument == null) //all contracts { s.Send("ALL"); } else //an actual search { s.SendMore("SEARCH"); //first we send a search request //then we need to serialize and send the instrument s.Send(MyUtils.ProtoBufSerialize(instrument, ms)); } //first we receive the size of the final uncompressed byte[] array bool hasMore; byte[] sizeBuffer = s.Receive(out hasMore); if (sizeBuffer.Length == 0) { RaiseEvent(Error, this, new ErrorArgs(-1, "Contract request failed, received no reply.")); return(new List <Instrument>()); } int outputSize = BitConverter.ToInt32(sizeBuffer, 0); //then the actual data byte[] buffer = s.Receive(out hasMore); if (buffer.Length == 0) { RaiseEvent(Error, this, new ErrorArgs(-1, "Contract request failed, received no data.")); return(new List <Instrument>()); } try { //then we process it by first decompressing ms.SetLength(0); byte[] decoded = LZ4Codec.Decode(buffer, 0, buffer.Length, outputSize); ms.Write(decoded, 0, decoded.Length); ms.Position = 0; //and finally deserializing return(Serializer.Deserialize <List <Instrument> >(ms)); } catch (Exception ex) { RaiseEvent(Error, this, new ErrorArgs(-1, "Error processing instrument data: " + ex.Message)); return(new List <Instrument>()); } } }
/// <summary> /// connects to the broker, if a socket already exists it will be disposed and /// a new socket created and connected (Linger is set to 1) /// The Client connects to broker using a DEALER socket /// </summary> private void Connect() { if (!ReferenceEquals(m_client, null)) { DisposeClient(); } m_client = new DealerSocket(); // sets a low linger to avoid port exhaustion, messages can be lost since it'll be sent again m_client.Options.Linger = m_lingerTime; if (m_identity != null) m_client.Options.Identity = m_identity; // set timeout timer to reconnect if no message is received during timeout m_lastReceivedRequest = DateTime.UtcNow; m_timer.EnableAndReset(); // attach the event handler for incoming messages m_client.ReceiveReady += OnReceiveReady; m_client.SendReady += OnSendReady; m_poller.Add(m_client); RotateBroker(); m_client.Connect(Address); m_connected = true; Log($"[CLIENT]: {m_client.Options.Identity} connecting to broker at {Address}"); }
/// <summary> /// connects to the broker, if a socket already exists it will be disposed and /// a new socket created and connected /// MDP requires a REQUEST socket for a client /// </summary> /// <exception cref="ApplicationException">NetMQContext must not be <c>null</c></exception> /// <exception cref="ApplicationException">if broker address is empty or <c>null</c></exception> private void Connect() { if (!ReferenceEquals (m_client, null)) m_client.Dispose (); if (ReferenceEquals (m_ctx, null)) throw new ApplicationException ("NetMQContext does not exist!"); m_client = m_ctx.CreateRequestSocket (); if (m_identity != null) m_client.Options.Identity = m_identity; // attach the event handler for incoming messages m_client.ReceiveReady += ProcessReceiveReady; m_client.Connect (m_brokerAddress); m_connected = true; Log (string.Format ("[CLIENT] connecting to broker at {0}", m_brokerAddress)); }
/// <summary> /// Connects to the validator /// </summary> public void Connect() { Socket.Connect(Address); Poller.RunAsync(); }
public void Connect() { if (context == null) { context = NetMQContext.Create(); } if (socket != null) { throw new NetMQException("Attempt to set socket that was already defined. This would prevent successful dispose of the context later on (since we can no longer close all sockets)."); } socket = context.CreateRequestSocket(); socket.Options.Linger = new TimeSpan(0, 0, 0, 1); socket.Connect("tcp://" + host + ":" + port); }
/// <summary> /// Connect or re-connect to the broker. /// </summary> private void Connect() { // if the socket exists dispose it and re-create one if (!ReferenceEquals(m_worker, null)) { DisposeWorker(); } m_worker = new DealerSocket(); // set identity if provided if (m_identity != null && m_identity.Length > 0) m_worker.Options.Identity = m_identity; m_timer.Interval = (int)HeartbeatDelay.TotalMilliseconds; m_timer.EnableAndReset(); // hook up the received message processing method before the socket is connected m_worker.ReceiveReady += ProcessReceiveReady; m_poller.Add(m_worker); m_worker.Connect(m_brokerAddress); Log($"[WORKER] connected to broker at {m_brokerAddress}"); // send READY to broker since worker is connected m_pollerQueue.Enqueue(() => Send(MDPCommand.Ready, m_serviceName, null)); // reset liveliness to active broker m_liveliness = _heartbeat_liveliness; // set point in time for next heatbeat m_heartbeatAt = DateTime.UtcNow + HeartbeatDelay; }
private void Connect() { _context = NetMQContext.Create(); _socket = _context.CreatePullSocket(); _socket.Connect(_publisherAddress); }
private void InternalStart() { m_isStoppedEvent.Reset(); IsRunning = true; m_monitoringSocket.Connect(Endpoint); }
private void ReceiveEvents(String subscriptionUri, String topic, CancellationToken cancellationToken) { using (NetMQContext context = NetMQContext.Create()) { using (NetMQSocket subscriberSocket = context.CreateSubscriberSocket()) { subscriberSocket.IgnoreErrors = true; subscriberSocket.Connect(subscriptionUri); subscriberSocket.Subscribe(topic); Logger.Info("ZeroMQCache: Connected to subscriptionUri \"{0}\".", subscriptionUri); // Eventhandler delegate to handle receiving messages subscriberSocket.ReceiveReady += (sender, args) => { try { if (args.ReceiveReady) { // Recieve and relay NetMQMessage netMQmessage = args.Socket.ReceiveMessage(); // Recieve the message ZeroMQMessage message = new ZeroMQMessage() { Topic = netMQmessage.Pop().ConvertToString(), Client = netMQmessage.Pop().ConvertToString(), Content = netMQmessage.Pop().ConvertToString() }; Logger.Debug("ZeroMQCache: Received -> {0}", message.ToString()); XmlCacheEvent cacheEvent = XmlCacheEvent.FromXml(message.Content); if (cacheEvent != null) { OnCacheEvent(cacheEvent.CacheRegion, cacheEvent.Key, cacheEvent.EventType); } } } catch (OperationCanceledException) { // We have been asked to cancel operation return; } catch (Exception ex) { Logger.Error("ZeroMQCache: Error receiving message.", ex); } }; while (!cancellationToken.IsCancellationRequested) { try { subscriberSocket.Poll(TimeSpan.FromSeconds(1)); } catch (OperationCanceledException) { // We have been asked to cancel operation break; } catch (Exception ex) { Logger.Error("ZeroMQCache: Error polling for messages.", ex); } } // Close socket subscriberSocket.Close(); } context.Terminate(); } }
/// <summary> /// connects to the broker, if a socket already exists it will be disposed and /// a new socket created and connected /// MDP requires a REQUEST socket for a client /// </summary> /// <exception cref="ApplicationException">NetMQContext must not be <c>null</c></exception> /// <exception cref="ApplicationException">if broker address is empty or <c>null</c></exception> private void Connect () { if (!ReferenceEquals (m_client, null)) m_client.Dispose (); m_client = new RequestSocket (); if (m_identity != null) m_client.Options.Identity = m_identity; // attach the event handler for incoming messages m_client.ReceiveReady += ProcessReceiveReady; m_client.Connect (m_brokerAddress); m_connected = true; Log ($"[CLIENT] connecting to broker at {m_brokerAddress}"); }
/// <summary> /// Connect or re-connect to the broker. /// </summary> private void Connect() { // if the socket exists dispose it and re-create one if (!ReferenceEquals(m_worker, null)) { m_worker.Unbind(m_brokerAddress); m_worker.Dispose(); } m_worker = m_ctx.CreateDealerSocket(); // set identity if provided if (m_identity != null && m_identity.Length > 0) m_worker.Options.Identity = m_identity; // hook up the received message processing method before the socket is connected m_worker.ReceiveReady += ProcessReceiveReady; m_worker.Connect(m_brokerAddress); Log(string.Format("[WORKER] connected to broker at {0}", m_brokerAddress)); // signal that worker is connected m_connected = true; // send READY to broker since worker is connected Send(MDPCommand.Ready, m_serviceName, null); // reset liveliness to active broker m_liveliness = _HEARTBEAT_LIVELINESS; // set point in time for next heartbeat m_heartbeatAt = DateTime.UtcNow + HeartbeatDelay; }
/// <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(); }