PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/NodeRxTestClient/Program.cs

#
C# | 39 lines | 34 code | 5 blank | 0 comment | 0 complexity | bfc6aa5ef954af50c5621e9e68443f77 MD5 | raw file
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Reactive;
  6. using System.Reactive.Linq;
  7. using System.Text;
  8. namespace NodeRxTestClient {
  9. class Program {
  10. static void Main(string[] args) {
  11. var ipAddress = IPAddress.Loopback;
  12. var port = 1001;
  13. var message = Encoding.ASCII.GetBytes("Hello, world!");
  14. var connect = Observable.Defer(() =>
  15. Observable.Using(() => new TcpClient(), client =>
  16. AsyncConnect(client, ipAddress, port)
  17. .Select(_ => client.GetStream())
  18. .SelectMany(stream => AsyncWrite(stream, message).Finally(stream.Flush))))
  19. .Repeat(10);
  20. using (connect.Subscribe()) {
  21. Console.WriteLine("Press ENTER to stop connecting.");
  22. Console.ReadLine();
  23. }
  24. }
  25. static IObservable<Unit> AsyncConnect(TcpClient client, IPAddress ipAddress, int port) {
  26. var connect = Observable.FromAsyncPattern<IPAddress, int>(client.BeginConnect, client.EndConnect);
  27. return Observable.Defer(() => connect(ipAddress, port));
  28. }
  29. static IObservable<Unit> AsyncWrite(Stream stream, byte[] bytes) {
  30. var write = Observable.FromAsyncPattern<byte[], int, int>(stream.BeginWrite, stream.EndWrite);
  31. return write(bytes, 0, bytes.Length);
  32. }
  33. }
  34. }