static async Task Main(string[] args) { var options = ((Parsed <Options>)Parser.Default.ParseArguments <Options>(args)).Value; var token = CancellationToken.None; using var loggerFactory = new LoggerFactory(); await using var transport = new TcpTransport(loggerFactory.CreateLogger("TCP local")); var messages = transport.BindAsync(IPEndPoint.Parse(options.LocalEndpoint), token); var reader = Task.Run(async() => { await foreach (var incoming in messages.WithCancellation(token)) { using var msg = incoming; var text = Encoding.UTF8.GetString(msg.Payload.FirstSpan); Console.WriteLine($"Received message from '{msg.Endpoint}': {text}"); } }); Console.WriteLine($"Local host started at {transport.LocalEndpoint} ..."); var endpoints = new List <IPEndPoint>(); foreach (var hostWithPort in options.SeedNodes) { var endpoint = IPEndPoint.Parse(hostWithPort); endpoints.Add(endpoint); } Console.WriteLine("Ready to receive messages..."); var userText = ""; do { Console.Write("> "); userText = Console.ReadLine(); var bytes = new ReadOnlySequence <byte>(Encoding.UTF8.GetBytes(userText)); foreach (var endpoint in endpoints) { await transport.SendAsync(endpoint, bytes, token); Console.WriteLine($"Sent '{userText}' to {endpoint}..."); } } while (userText != "quit"); }
public async Task TCP_transport_should_receive_messages_from_remote_endpoint() { using var cts = new CancellationTokenSource(10_000); var token = cts.Token; //var token = CancellationToken.None; var expected = Enumerable.Range(0, 10) .Select(i => "hello " + i.ToString()) .ToArray(); var messages = local.BindAsync(localEndpoint, token); // simulate two communicating nodes using two separate Tasks var localProcess = Task.Run(async() => { var i = 0; await foreach (var message in messages.WithCancellation(token)) { using var incoming = message; var payload = Encoding.UTF8.GetString(incoming.Payload.FirstSpan); payload.Should().Be(expected[i]); i++; if (i == expected.Length) { break; } } }, token); var remoteProcess = Task.Run(async() => { await using var remote = new TcpTransport(output.LoggerFor <TcpTransport>("remote")); foreach (var message in expected) { var payload = new ReadOnlySequence <byte>(Encoding.UTF8.GetBytes(message)); await remote.SendAsync((IPEndPoint)local.LocalEndpoint, payload, token); } }, token); await Task.WhenAll(localProcess, remoteProcess); }