Guest User

Untitled

a guest
Feb 25th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.61 KB | None | 0 0
  1. namespace AaronLuna.TplSockets
  2. {
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8.  
  9. public class TplSocketExample
  10. {
  11. const int BufferSize = 8 * 1024;
  12. const int ConnectTimeoutMs = 3000;
  13. const int ReceiveTimeoutMs = 3000;
  14. const int SendTimeoutMs = 3000;
  15.  
  16. Socket _listenSocket;
  17. Socket _clientSocket;
  18. Socket _transferSocket;
  19.  
  20. public async Task<Result> SendAndReceiveTextMesageAsync()
  21. {
  22. _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  23. _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  24. _transferSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  25.  
  26. var serverPort = 7003;
  27. var ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
  28. var ipAddress = ipHostInfo.AddressList.Select(ip => ip)
  29. .FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
  30. var ipEndPoint = new IPEndPoint(ipAddress, serverPort);
  31.  
  32. // Step 1: Bind a socket to a local TCP port and Listen for incoming connections
  33. _listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  34. _listenSocket.Bind(ipEndPoint);
  35. _listenSocket.Listen(5);
  36.  
  37. // Step 2: Create a Task and accept the next incoming connection (ServerAcceptTask)
  38. // NOTE: This call is not awaited so the method continues executing
  39. var acceptTask = Task.Run(AcceptConnectionTask);
  40.  
  41. // Step 3: With another socket, connect to the bound socket and await the result (ClientConnectTask)
  42. var connectResult =
  43. await _clientSocket.ConnectWithTimeoutAsync(ipAddress.ToString(), serverPort, ConnectTimeoutMs)
  44. .ConfigureAwait(false);
  45.  
  46. // Step 4: Await the result of the ServerAcceptTask
  47. var acceptResult = await acceptTask.ConfigureAwait(false);
  48.  
  49. // If either ServerAcceptTask or ClientConnectTask did not complete successfully,stop execution and report the error
  50. if (Result.Combine(acceptResult, connectResult).Failure)
  51. {
  52. return Result.Fail("There was an error connecting to the server/accepting connection from the client");
  53. }
  54.  
  55. // Step 5: Store the transfer socket if ServerAcceptTask was successful
  56. _transferSocket = acceptResult.Value;
  57.  
  58. // Step 6: Create a Task and recieve data from the transfer socket (ServerReceiveBytesTask)
  59. // NOTE: This call is not awaited so the method continues executing
  60. var receiveTask = Task.Run(ReceiveMessageAsync);
  61.  
  62. // Step 7: Encode a string message before sending it to the server
  63. var messageToSend = "this is a text message from a socket";
  64. var messageData = Encoding.ASCII.GetBytes(messageToSend);
  65.  
  66. // Step 8: Send the message data to the server and await the result (ClientSendBytesTask)
  67. var sendResult =
  68. await _clientSocket.SendWithTimeoutAsync(messageData, 0, messageData.Length, 0, SendTimeoutMs)
  69. .ConfigureAwait(false);
  70.  
  71. // Step 9: Await the result of ServerReceiveBytesTask
  72. var receiveResult = await receiveTask.ConfigureAwait(false);
  73.  
  74. // Step 10: If either ServerReceiveBytesTask or ClientSendBytesTask did not complete successfully,stop execution and report the error
  75. if (Result.Combine(sendResult, receiveResult).Failure)
  76. {
  77. return Result.Fail("There was an error sending/receiving data from the client");
  78. }
  79.  
  80. // Step 11: Compare the string that was received to what was sent, report an error if not matching
  81. var messageReceived = receiveResult.Value;
  82. if (messageToSend != messageReceived)
  83. {
  84. return Result.Fail("Error: Message received from client did not match what was sent");
  85. }
  86.  
  87. // Step 12: Report the entire task was successful since all subtasks were successful
  88. return Result.Ok();
  89. }
  90.  
  91. async Task<Result<Socket>> AcceptConnectionTask()
  92. {
  93. return await _listenSocket.AcceptAsync().ConfigureAwait(false);
  94. }
  95.  
  96. async Task<Result<string>> ReceiveMessageAsync()
  97. {
  98. var message = string.Empty;
  99. var buffer = new byte[BufferSize];
  100.  
  101. var receiveResult =
  102. await _transferSocket.ReceiveWithTimeoutAsync(buffer, 0, BufferSize, 0, ReceiveTimeoutMs)
  103. .ConfigureAwait(false);
  104.  
  105. var bytesReceived = receiveResult.Value;
  106. if (bytesReceived == 0)
  107. {
  108. return Result.Fail<string>("Error reading message from client, no data was received");
  109. }
  110.  
  111. message = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
  112.  
  113. return Result.Ok(message);
  114. }
  115. }
  116. }
Add Comment
Please, Sign In to add comment