Guest User

Untitled

a guest
Nov 24th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ConsoleApp1
  8. {
  9. class Program
  10. {
  11. class A
  12. {
  13. public int X { get; set; }
  14. public string Y { get; set; }
  15. }
  16.  
  17. static async Task ReceiveLoop(TcpClient client)
  18. {
  19. using (client)
  20. using (var stream = client.GetStream())
  21. {
  22. while (true)
  23. {
  24. object obj = await stream.ReadObjectAsync();
  25. if (obj == null)
  26. break;
  27. Console.WriteLine($"server received object: {obj.GetType()} {JsonConvert.SerializeObject(obj)}");
  28. await stream.WriteObjectAsync("received success");
  29. }
  30. Console.WriteLine("connection closed");
  31. }
  32. }
  33.  
  34. static async Task Server(IPAddress addr, int port)
  35. {
  36. var listener = new TcpListener(addr, port);
  37. listener.Start();
  38. while (true)
  39. ReceiveLoop(await listener.AcceptTcpClientAsync());
  40. }
  41.  
  42. static async Task Client(string addr, int port)
  43. {
  44. using (var client = new TcpClient())
  45. {
  46. await client.ConnectAsync(addr, port);
  47. using (var stream = client.GetStream())
  48. {
  49. await stream.WriteObjectAsync(new A() { X = 123, Y = "abc" });
  50. var obj = await stream.ReadObjectAsync();
  51. Console.WriteLine(obj);
  52. }
  53. }
  54. }
  55.  
  56. static void Main(string[] args)
  57. {
  58. Task.Run(() => Server(IPAddress.Any, 8888));
  59. Task.Run(() => Client("127.0.0.1", 8888));
  60. Task.Run(() => Client("127.0.0.1", 8888));
  61. Console.ReadLine();
  62. }
  63. }
  64. }
Add Comment
Please, Sign In to add comment