private static void Main() { using (var frontend = new RouterSocket("@tcp://127.0.0.1:5559")) using (var backend = new DealerSocket("@tcp://127.0.0.1:5560")) { // Handler for messages coming in to the frontend frontend.ReceiveReady += (s, e) => { var msg = e.Socket.ReceiveMultipartMessage(); backend.SendMultipartMessage(msg); // Relay this message to the backend }; // Handler for messages coming in to the backend backend.ReceiveReady += (s, e) => { var msg = e.Socket.ReceiveMultipartMessage(); frontend.SendMultipartMessage(msg); // Relay this message to the frontend }; using (var poller = new NetMQPoller {backend, frontend}) { // Listen out for events on both sockets and raise events when messages come in poller.Run(); } } }
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 MessageTest() { Action<Codec> setMessage = m => { m.Id = Codec.MessageId.Message; m.Message.MessageId = 123; m.Message.RelatedMessageId = 123; m.Message.Service = "Life is short but Now lasts for ever"; m.Message.Subject = "Life is short but Now lasts for ever"; m.Message.Body = Encoding.ASCII.GetBytes("Captcha Diem"); m.Message.OneWay = 123; m.Message.ConnectionId = 123; }; Action<Codec> checkMessage = m=> { Assert.That(m.Id, Is.EqualTo(Codec.MessageId.Message)); Assert.That(m.Message.MessageId, Is.EqualTo(123)); Assert.That(m.Message.RelatedMessageId, Is.EqualTo(123)); Assert.That(m.Message.Service, Is.EqualTo("Life is short but Now lasts for ever")); Assert.That(m.Message.Subject, Is.EqualTo("Life is short but Now lasts for ever")); Assert.That(m.Message.Body, Is.EqualTo(Encoding.ASCII.GetBytes("Captcha Diem"))); Assert.That(m.Message.OneWay, Is.EqualTo(123)); Assert.That(m.Message.ConnectionId, Is.EqualTo(123)); }; using (var client = new DealerSocket("inproc://zprototest")) using (var server = new RouterSocket("inproc://zprototest")) { Codec clientMessage = new Codec(); Codec serverMessage = new Codec(); 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); } } }
public AsyncBrocker(NetMQContext context, string address) { _socket = context.CreateDealerSocket(); _socket.Options.SendHighWatermark = 1; _socket.Options.ReceiveHighWatermark = 1; _socket.Bind(address); _socket.ReceiveReady += SocketReceiveReady; _poller.AddSocket(_socket); _poller.PollTillCancelledNonBlocking(); }
/// <summary> /// Initializes an instance of a NetMQSender with the specified RequestSocket and binary serializer /// </summary> /// <param name="requestSocket"></param> /// <param name="binarySerializer"></param> public NetMQSender(DealerSocket dealerSocket, ISerializer<byte[]> binarySerializer, String address) { if (binarySerializer == null) throw new ArgumentNullException("ISerializer<byte[]>"); if (dealerSocket == null) throw new ArgumentNullException("DealerSocket"); if (address == null || address == default(String) || address.Length == 0) throw new ArgumentNullException("Address"); this.binarySerializer = binarySerializer; this.dealerSocket = dealerSocket; this.address = address; }
public void TwoMessagesFromRouterToDealer() { using (var server = new RouterSocket()) using (var client = new DealerSocket()) using (var poller = new NetMQPoller { client }) { var port = server.BindRandomPort("tcp://*"); client.Connect("tcp://127.0.0.1:" + port); var cnt = 0; client.ReceiveReady += (sender, e) => { var strs = e.Socket.ReceiveMultipartStrings(); foreach (var str in strs) { Console.WriteLine(str); } cnt++; if (cnt == 2) { poller.Stop(); } }; byte[] clientId = Encoding.Unicode.GetBytes("ClientId"); client.Options.Identity = clientId; const string request = "GET /\r\n"; const string response = "HTTP/1.0 200 OK\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "Hello, World!"; client.SendFrame(request); byte[] serverId = server.ReceiveFrameBytes(); Assert.AreEqual(request, server.ReceiveFrameString()); // two messages in a row, not frames server.SendMoreFrame(serverId).SendFrame(response); server.SendMoreFrame(serverId).SendFrame(response); poller.Run(); } }
public void RouterMandatoryFalseDiscardsMessageSilently() { { using (var dealer = new DealerSocket()) { dealer.Options.Identity = Encoding.ASCII.GetBytes("dealer"); dealer.Bind("tcp://localhost:6667"); using (var router = new RouterSocket()) { router.Connect("tcp://localhost:8889"); Assert.DoesNotThrow(() => router.SendMoreFrame("dealer").SendFrame("Hello")); } } } }
public void CheckTrySendSucceeds() { using (var router = new RouterSocket()) using (var dealer = new DealerSocket()) { var port = router.BindRandomPort("tcp://127.0.0.1"); router.Options.Linger = TimeSpan.Zero; dealer.Options.SendHighWatermark = 1; dealer.Options.Linger = TimeSpan.Zero; dealer.Connect("tcp://127.0.0.1:" + port); Thread.Sleep(100); Assert.IsTrue(dealer.TrySendFrame("1")); } }
public void RemoveTimer() { using (var router = new RouterSocket()) using (var dealer = new DealerSocket()) using (var poller = new Poller(router) { PollTimeout = TestPollTimeoutMillis }) { int port = router.BindRandomPort("tcp://127.0.0.1"); dealer.Connect("tcp://127.0.0.1:" + port); bool timerTriggered = false; var timer = new NetMQTimer(TimeSpan.FromMilliseconds(100)); timer.Elapsed += (a, s) => { timerTriggered = true; }; // The timer will fire after 100ms poller.AddTimer(timer); bool messageArrived = false; router.ReceiveReady += (s, e) => { router.SkipFrame(); router.SkipFrame(); messageArrived = true; // Remove timer poller.RemoveTimer(timer); }; poller.PollTillCancelledNonBlocking(); Thread.Sleep(20); dealer.SendFrame("hello"); Thread.Sleep(300); poller.CancelAndJoin(); Assert.IsTrue(messageArrived); Assert.IsFalse(timerTriggered); } }
public void ServiceRegisterTest() { Action <Codec> setMessage = m => { m.Id = Codec.MessageId.ServiceRegister; m.ServiceRegister.Service = "Life is short but Now lasts for ever"; }; Action <Codec> checkMessage = m => { Assert.That(m.Id, Is.EqualTo(Codec.MessageId.ServiceRegister)); Assert.That(m.ServiceRegister.Service, Is.EqualTo("Life is short but Now lasts for ever")); }; using (var client = new DealerSocket("inproc://zprototest")) using (var server = new RouterSocket("inproc://zprototest")) { Codec clientMessage = new Codec(); Codec serverMessage = new Codec(); 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); } } }
/// <summary> /// Cleans up resources /// </summary> private void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { TerminateConnection(); if (!(socket is null)) { socket.ReceiveReady -= PendingMessage; socket.Dispose(); } socket = null; } disposedValue = true; } }
public void AddAddress_WithAlreadyAddedAddress_DoesNothing() { // Arrange var socket = new DealerSocket(); var sender = new NetMQSender(socket, messageFactory); sender.AddAddress(address); // Act sender.AddAddress(address); // Assert Assert.That(sender.Addresses, Has.Count.EqualTo(1)); Assert.That(sender.Addresses, Has.Exactly(1).EqualTo(address)); // Cleanup sender.Dispose(); }
public void RouterMandatoryTrueThrowsHostUnreachableException() { { using (var dealer = new DealerSocket()) { dealer.Options.Identity = Encoding.ASCII.GetBytes("dealer"); dealer.Bind("tcp://localhost:6667"); using (var router = new RouterSocket()) { router.Options.RouterMandatory = true; router.Connect("tcp://localhost:8889"); Assert.Throws <HostUnreachableException>(() => router.SendMoreFrame("dealer").SendFrame("Hello")); } } } }
public void Remove_WithAddedAddress_IsConnectedFalse() { // Arrange var socket = new DealerSocket(); var sender = new NetMQSender(socket, messageFactory); var address = TcpAddress.Wildcard(5555); sender.AddAddress(address); // Act sender.RemoveAddress(address); // Assert Assert.That(sender.IsConnected, Is.False); // Cleanup sender.Dispose(); }
public void Addresses_WhenDisposed_ThrowsInvalidOperationException() { // Arrange var socket = new DealerSocket(); var sender = new NetMQSender(socket, messageFactory); var address = TcpAddress.Wildcard(5555); sender.Dispose(); // Act void AddAddress() => sender.AddAddress(address); // Assert Assert.That(AddAddress, Throws.TypeOf <InvalidOperationException>()); // Cleanup sender.Dispose(); }
public void CheckSendAgainException() { using (var router = new RouterSocket()) using (var dealer = new DealerSocket()) { var port = router.BindRandomPort("tcp://127.0.0.1"); router.Options.Linger = TimeSpan.Zero; dealer.Options.SendHighWatermark = 1; dealer.Options.Linger = TimeSpan.Zero; dealer.Connect("tcp://127.0.0.1:" + port); #pragma warning disable 618 dealer.Send("1", dontWait: true, sendMore: false); dealer.Send("2", dontWait: true, sendMore: false); #pragma warning restore 618 } }
public void BindToLocal() { var validAliasesForLocalHost = new[] { "127.0.0.1", "localhost", Dns.GetHostName() }; foreach (var alias in validAliasesForLocalHost) { using (var localDealer = new DealerSocket()) using (var connectingDealer = new DealerSocket()) { var port = localDealer.BindRandomPort("tcp://*"); connectingDealer.Connect($"tcp://{alias}:{port}"); localDealer.SendFrame("test"); Assert.AreEqual("test", connectingDealer.ReceiveFrameString()); } } }
public virtual void Start() { var connectto = config.ResponseSocketString; //在检测到 ResponseSocketString 是已 @开头的 自己内置一个LRUBroker if (config.ResponseSocketString.StartsWith("@")) { var dealer = new DealerSocket("@inproc://backend"); _broker = new Proxy(new RouterSocket(config.ResponseSocketString), dealer); // new LRUBroker(config.ResponseSocketString, "tcp://*"); connectto = $">inproc://backend"; if (Logger.IsTraceEnabled) { Logger.Trace($"start inner req/rep proxy"); } } var pubConnectTo = config.PublisherSocketString; //if (config.PublisherSocketString.StartsWith("@")) //{ // _pubBroker = new Proxy(new XSubscriberSocket(config.PublisherSocketString), new XPublisherSocket("@inproc://pubbackend")); // pubConnectTo = $">inproc://pubbackend"; // if (Logger.IsTraceEnabled) // Logger.Trace($"start inner sub/pub proxy"); //} if (_broker != null) { Task.Factory.StartNew(_broker.Start); } if (_pubBroker != null) { Task.Factory.StartNew(_pubBroker.Start); } _actorService.Start(); for (int i = 0; i < config.BackendWorkersPerService; i++) { ThreadWorkers.Add(Task.Factory.StartNew(WorkerTask, connectto, _c_token.Token)); } PublisherSocket = new PublisherSocket(pubConnectTo); }
private void StopRealTimeRequestSocket() { lock (realTimeRequestSocketLock) { if (realTimeRequestSocket != null) { try { realTimeRequestSocket.Disconnect(realTimeRequestConnectionString); } finally { realTimeRequestSocket.ReceiveReady -= RealTimeRequestSocketReceiveReady; realTimeRequestSocket.Close(); realTimeRequestSocket = null; } } } }
public void Start() { using (_dealer = new DealerSocket()) { _dealer.Bind(_dealerEndpoint); using (_router = new RouterSocket(_routerEndpoint)) { while (!_cancel.IsCancellationRequested) { var msg = _router.ReceiveMultipartMessage(); _dealer.SendFrame(msg[1].Buffer); Handled++; } } } }
public IEnumerable <DeviceStatus> GetDevices() { var reqSock = new DealerSocket(">inproc://queryRouter"); reqSock.SendReady += (o, e) => { e.Socket.SendFrame("SendStatus"); }; reqSock.Poll(); string msg; var results = new List <DeviceStatus>(); while (reqSock.TryReceiveFrameString(TimeSpan.FromSeconds(1), out msg)) { results.Add(JsonConvert.DeserializeObject <DeviceStatus>(msg)); } return(results); }
private void StopHistoricalDataSocket() { lock (historicalDataSocket) { if (historicalDataSocket != null) { try { historicalDataSocket.Disconnect(historicalDataConnectionString); } finally { historicalDataSocket.ReceiveReady -= HistoricalDataSocketReceiveReady; historicalDataSocket.Close(); historicalDataSocket = null; } } } }
public void StartAgainAfterStop() { using (var front = new RouterSocket()) using (var back = new DealerSocket()) { front.Bind("inproc://frontend"); back.Bind("inproc://backend"); var proxy = new Proxy(front, back); Task.Factory.StartNew(proxy.Start); // Send a message through to ensure the proxy has started using (var client = new RequestSocket()) using (var server = new ResponseSocket()) { client.Connect("inproc://frontend"); server.Connect("inproc://backend"); client.SendFrame("hello"); Assert.AreEqual("hello", server.ReceiveFrameString()); server.SendFrame("reply"); Assert.AreEqual("reply", client.ReceiveFrameString()); } proxy.Stop(); // blocks until stopped // Start it again Task.Factory.StartNew(proxy.Start); // Send a message through to ensure the proxy has started using (var client = new RequestSocket()) using (var server = new ResponseSocket()) { client.Connect("inproc://frontend"); server.Connect("inproc://backend"); client.SendFrame("hello"); Assert.AreEqual("hello", server.ReceiveFrameString()); server.SendFrame("reply"); Assert.AreEqual("reply", client.ReceiveFrameString()); } proxy.Stop(); // blocks until stopped } }
void VentilatorQuery_SendQuery(DealerSocket ventilatorQuery, RouterSocket query) { #region communication ventilatorQuery to Querier var msgQuery = new NetMQMessage(); msgQuery.AppendEmptyFrame(); msgQuery.Append("HELLO"); ventilatorQuery.SendMultipartMessage(msgQuery); _testOutputHelper.WriteLine("Send Hello to query processor"); Task.Delay(1000); var messageQueryID = query.ReceiveFrameString(); query.ReceiveFrameString(); var messageQueryCommand = query.ReceiveFrameString(); _testOutputHelper.WriteLine("Received Query: {0} {1}", messageQueryID, messageQueryCommand); #endregion }
public void SeparateControlSocketsObservedMessages() { using (var front = new RouterSocket()) using (var back = new DealerSocket()) using (var controlInPush = new PushSocket()) using (var controlInPull = new PullSocket()) using (var controlOutPush = new PushSocket()) using (var controlOutPull = new PullSocket()) { front.Bind("inproc://frontend"); back.Bind("inproc://backend"); controlInPush.Bind("inproc://controlIn"); controlInPull.Connect("inproc://controlIn"); controlOutPush.Bind("inproc://controlOut"); controlOutPull.Connect("inproc://controlOut"); var proxy = new Proxy(front, back, controlInPush, controlOutPush); Task.Factory.StartNew(proxy.Start); using (var client = new RequestSocket()) using (var server = new ResponseSocket()) { client.Connect("inproc://frontend"); server.Connect("inproc://backend"); client.SendFrame("hello"); Assert.AreEqual("hello", server.ReceiveFrameString()); server.SendFrame("reply"); Assert.AreEqual("reply", client.ReceiveFrameString()); } Assert.IsNotNull(controlInPull.ReceiveFrameBytes()); // receive identity Assert.IsEmpty(controlInPull.ReceiveFrameString()); // pull terminator Assert.AreEqual("hello", controlInPull.ReceiveFrameString()); Assert.IsNotNull(controlOutPull.ReceiveFrameBytes()); // receive identity Assert.IsEmpty(controlOutPull.ReceiveFrameString()); // pull terminator Assert.AreEqual("reply", controlOutPull.ReceiveFrameString()); proxy.Stop(); } }
/// <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.ReceiveReady += OnWorkerReceiveReady; 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); }
void VentilatorCommand_SendCommand(DealerSocket ventilatorCommand, RouterSocket command) { #region communication ventilatorCommand to Commander var msgCommand = new NetMQMessage(); msgCommand.AppendEmptyFrame(); msgCommand.Append("HELLO"); ventilatorCommand.SendMultipartMessage(msgCommand); _testOutputHelper.WriteLine("Send Hello to command processor"); Task.Delay(1000); var messageCommandID = command.ReceiveFrameString(); command.ReceiveFrameString(); var messageCommandCommand = command.ReceiveFrameString(); _testOutputHelper.WriteLine("Received Command: {0} {1}", messageCommandID, messageCommandCommand); #endregion }
public void BindToLocal() { var validAliasesForLocalHost = new[] { "127.0.0.1", "localhost", Dns.GetHostName() }; foreach (var alias in validAliasesForLocalHost) { using (var localDealer = new DealerSocket()) using (var connectingDealer = new DealerSocket()) { var port = localDealer.BindRandomPort("tcp://*"); connectingDealer.Connect(string.Format("tcp://{0}:{1}", alias, port)); localDealer.SendFrame("test"); Assert.AreEqual("test", connectingDealer.ReceiveFrameString()); Console.WriteLine(alias + " connected "); } } }
private static object dealer_Lock = new object(); //锁同步 public DealerService() { lock (dealer_Lock) { if (dealer == null) { dealer = new DealerSocket(); //dealer.Connect("tcp://192.168.0.21:5556") dealer.Connect(ManagerHelp.IP); //等待时间10秒 //dealer.Options.Linger=new TimeSpan(0,0,10); string commID = Guid.NewGuid().ToString(); dealer.Options.Identity = Encoding.UTF8.GetBytes(commID); Task.Factory.StartNew(state => { Receive(); }, TaskCreationOptions.LongRunning); } } }
static void Main(string[] args) { Console.WriteLine("====== WORKER ======"); using (var pull = new PullSocket()) using (var sink = new DealerSocket()) { pull.Connect("tcp://127.0.0.1:8888"); sink.Connect("tcp://127.0.0.1:7777"); while (true) { var workload = pull.ReceiveFrameString(); Thread.Sleep(int.Parse(workload)); Console.WriteLine("Sending to Sink"); sink.SendFrame(string.Empty); } } }
public async Task 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(); Task.Factory.StartNew(() => HandleKeyData_DealerReceive(kd.Key, kd.DataString)); } catch (Exception ex) { LogUtil.Error($"Dealer-Receive消息执行异常:{ex.Message}"); } } } }
public static AppProtocolVersion QueryAppProtocolVersionNetMQ( this BoundPeer peer, TimeSpan?timeout = null ) { using var dealerSocket = new DealerSocket(ToNetMQAddress(peer)); var key = new PrivateKey(); var ping = new Ping(); var netMQMessageCodec = new NetMQMessageCodec(); NetMQMessage request = netMQMessageCodec.Encode( ping, key, new Peer(key.PublicKey), DateTimeOffset.UtcNow, default ); TimeSpan timeoutNotNull = timeout ?? TimeSpan.FromSeconds(5); try { if (dealerSocket.TrySendMultipartMessage(timeoutNotNull, request)) { var response = new NetMQMessage(); if (dealerSocket.TryReceiveMultipartMessage(timeoutNotNull, ref response)) { return(AppProtocolVersion.FromToken(response.First.ConvertToString())); } } } catch (TerminatingException) { throw new TimeoutException($"Peer didn't respond."); } throw new TimeoutException( $"Peer[{peer}] didn't respond within the specified time[{timeout}]." ); }
public void Remove_WithAddedAddress_IsConnectedTrue() { // Arrange var socket = new DealerSocket(); var sender = new NetMQSender(socket, messageFactory); var address = TcpAddress.Wildcard(5555); var address2 = TcpAddress.Wildcard(5556); sender.AddAddress(address); sender.AddAddress(address2); sender.InitializeConnection(); // Act sender.RemoveAddress(address); // Assert Assert.That(sender.IsConnected, Is.True); // Cleanup sender.TerminateConnection(); sender.Dispose(); }
public void SendHelloTest() { using (var mailbox = new RouterSocket("tcp://127.0.0.1:5551")) // RouterSocket default action binds to the address using (var socket = new DealerSocket("tcp://127.0.0.1:5551")) // DealerSocket default action connects to the address { var clientId = Encoding.Unicode.GetBytes("ClientId"); socket.Options.Identity = clientId; ZreMsg.SendHello(socket, 1, "tcp://127.0.0.1:5552", new List <string>(), 0, "TestHello", new Dictionary <string, string>()); var msg = new ZreMsg(); msg.Receive(mailbox); var routingEqual = msg.RoutingId.SequenceEqual(clientId); routingEqual.Should().BeTrue(); var hello = msg.Hello; hello.Version.Should().Be(2); hello.Sequence.Should().Be(1); hello.Endpoint.Should().Be("tcp://127.0.0.1:5552"); hello.Status.Should().Be(0); hello.Name.Should().Be("TestHello"); hello.Headers.Count.Should().Be(0); } }
public void Disconnect() { if (_connected) { _mailbox.Disconnect(_endpoint); _mailbox.Dispose(); _mailbox = null; _endpoint = null; _ready = false; _connected = false; } }
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 void ErrorTest() { Action<Codec> setMessage = m => { m.Id = Codec.MessageId.Error; m.Error.RelatedMessageId = 123; m.Error.ConnectionId = 123; }; Action<Codec> checkMessage = m=> { Assert.That(m.Id, Is.EqualTo(Codec.MessageId.Error)); Assert.That(m.Error.RelatedMessageId, Is.EqualTo(123)); Assert.That(m.Error.ConnectionId, Is.EqualTo(123)); }; using (var client = new DealerSocket("inproc://zprototest")) using (var server = new RouterSocket("inproc://zprototest")) { Codec clientMessage = new Codec(); Codec serverMessage = new Codec(); 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); } } }
public void ServiceRegisterTest() { Action<Codec> setMessage = m => { m.Id = Codec.MessageId.ServiceRegister; m.ServiceRegister.Service = "Life is short but Now lasts for ever"; }; Action<Codec> checkMessage = m=> { Assert.That(m.Id, Is.EqualTo(Codec.MessageId.ServiceRegister)); Assert.That(m.ServiceRegister.Service, Is.EqualTo("Life is short but Now lasts for ever")); }; using (var client = new DealerSocket("inproc://zprototest")) using (var server = new RouterSocket("inproc://zprototest")) { Codec clientMessage = new Codec(); Codec serverMessage = new Codec(); 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 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(); } }
/// <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; }