public async Task RequestTest() { const string subject = "some_subject"; const string expectedReply = "some reply"; var encodedReply = Encoding.UTF8.GetBytes(expectedReply); string inbox = null, subscriptionId = null; var resetEvent = new ManualResetEvent(false); var messageSubject = new Subject <Message <IncomingMessage> >(); var mockNatsConnection = new Mock <INatsConnection>(); mockNatsConnection .Setup(x => x.Write(It.IsAny <byte[]>(), It.IsAny <CancellationToken>())) .Returns <byte[], CancellationToken>((data, _) => { var message = Encoding.UTF8.GetString(data); var match = Regex.Match(message, $"^PUB {subject} ([^ \r\n]+) [0-9]+\r\n.*"); if (match.Success) { inbox = match.Groups[1].Value; resetEvent.Set(); } else { match = Regex.Match(message, "^SUB _INBOX.[^ \r\n]+ ([^ \r\n]+)\r\n$"); if (match.Success) { subscriptionId = match.Groups[1].Value; } } return(Task.CompletedTask); }); mockNatsConnection.Setup(x => x.Messages).Returns(messageSubject); mockNatsConnection.Setup(x => x.OnConnect).Returns(Observable.Return(new ServerInfo())); using (var client = new NatsClient(mockNatsConnection.Object)) { var requestTask = client.Request(subject, _timeout); resetEvent.WaitOne(_timeout); Assert.False(string.IsNullOrEmpty(subscriptionId), "Client published request before subscribing for result"); var incomingMessage = new IncomingMessage(inbox, subscriptionId, string.Empty, encodedReply.Length, encodedReply); messageSubject.OnNext(Message.From("MSG", incomingMessage)); var reply = await requestTask; Assert.Equal(incomingMessage, reply); } }
public static async Task <IncomingMessage> Request(this NatsClient @this, string subject, string data, TimeSpan timeout) { var cancellationTokenSource = new CancellationTokenSource(timeout); return(await @this.Request(subject, data, cancellationTokenSource.Token)); }
public static async Task <IncomingMessage> Request(this NatsClient @this, string subject, string data, CancellationToken cancellationToken = default(CancellationToken)) { return(await @this.Request(subject, Encoding.UTF8.GetBytes(data), cancellationToken)); }
/// <summary> /// Sends greeting message to routers. /// </summary> /// <param name="callback">Callback on reponse.</param> public void SendRouterGreetings(SubscribeCallback callback) { NatsClient.Request("router.greet", null, callback, "{}"); }