PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/ayncio/ayncio/Program.cs

https://gitlab.com/llearn/csharp
C# | 169 lines | 108 code | 29 blank | 32 comment | 3 complexity | 0cd65e200f28fcf652d0b9ab0d8b274f MD5 | raw file
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading;
  6. // State object for reading client data asynchronously
  7. public class StateObject
  8. {
  9. // Client socket.
  10. public Socket workSocket = null;
  11. // Size of receive buffer.
  12. public const int BufferSize = 1024;
  13. // Receive buffer.
  14. public byte[] buffer = new byte[BufferSize];
  15. // Received data string.
  16. public StringBuilder sb = new StringBuilder();
  17. }
  18. public class AsynchronousSocketListener
  19. {
  20. // Thread signal.
  21. public static ManualResetEvent allDone = new ManualResetEvent(false);
  22. public AsynchronousSocketListener()
  23. {
  24. }
  25. public static void StartListening()
  26. {
  27. // Data buffer for incoming data.
  28. byte[] bytes = new Byte[1024];
  29. // Establish the local endpoint for the socket.
  30. // The DNS name of the computer
  31. // running the listener is "host.contoso.com".
  32. IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
  33. IPAddress ipAddress = ipHostInfo.AddressList[0];
  34. IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
  35. // Create a TCP/IP socket.
  36. Socket listener = new Socket(AddressFamily.InterNetwork,
  37. SocketType.Stream, ProtocolType.Tcp);
  38. // Bind the socket to the local endpoint and listen for incoming connections.
  39. try
  40. {
  41. listener.Bind(localEndPoint);
  42. listener.Listen(100);
  43. while (true)
  44. {
  45. // Set the event to nonsignaled state.
  46. allDone.Reset();
  47. // Start an asynchronous socket to listen for connections.
  48. Console.WriteLine("Waiting for a connection...");
  49. listener.BeginAccept(
  50. new AsyncCallback(AcceptCallback),
  51. listener);
  52. // Wait until a connection is made before continuing.
  53. allDone.WaitOne();
  54. }
  55. }
  56. catch (Exception e)
  57. {
  58. Console.WriteLine(e.ToString());
  59. }
  60. Console.WriteLine("\nPress ENTER to continue...");
  61. Console.Read();
  62. }
  63. public static void AcceptCallback(IAsyncResult ar)
  64. {
  65. // Signal the main thread to continue.
  66. allDone.Set();
  67. // Get the socket that handles the client request.
  68. Socket listener = (Socket)ar.AsyncState;
  69. Socket handler = listener.EndAccept(ar);
  70. // Create the state object.
  71. StateObject state = new StateObject();
  72. state.workSocket = handler;
  73. handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  74. new AsyncCallback(ReadCallback), state);
  75. }
  76. public static void ReadCallback(IAsyncResult ar)
  77. {
  78. String content = String.Empty;
  79. // Retrieve the state object and the handler socket
  80. // from the asynchronous state object.
  81. StateObject state = (StateObject)ar.AsyncState;
  82. Socket handler = state.workSocket;
  83. // Read data from the client socket.
  84. int bytesRead = handler.EndReceive(ar);
  85. if (bytesRead > 0)
  86. {
  87. // There might be more data, so store the data received so far.
  88. state.sb.Append(Encoding.ASCII.GetString(
  89. state.buffer, 0, bytesRead));
  90. // Check for end-of-file tag. If it is not there, read
  91. // more data.
  92. content = state.sb.ToString();
  93. if (content.IndexOf("<EOF>") > -1)
  94. {
  95. // All the data has been read from the
  96. // client. Display it on the console.
  97. Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
  98. content.Length, content);
  99. // Echo the data back to the client.
  100. Send(handler, content);
  101. }
  102. else
  103. {
  104. // Not all data received. Get more.
  105. handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  106. new AsyncCallback(ReadCallback), state);
  107. }
  108. }
  109. }
  110. private static void Send(Socket handler, String data)
  111. {
  112. // Convert the string data to byte data using ASCII encoding.
  113. byte[] byteData = Encoding.ASCII.GetBytes(data);
  114. // Begin sending the data to the remote device.
  115. handler.BeginSend(byteData, 0, byteData.Length, 0,
  116. new AsyncCallback(SendCallback), handler);
  117. }
  118. private static void SendCallback(IAsyncResult ar)
  119. {
  120. try
  121. {
  122. // Retrieve the socket from the state object.
  123. Socket handler = (Socket)ar.AsyncState;
  124. // Complete sending the data to the remote device.
  125. int bytesSent = handler.EndSend(ar);
  126. Console.WriteLine("Sent {0} bytes to client.", bytesSent);
  127. handler.Shutdown(SocketShutdown.Both);
  128. handler.Close();
  129. }
  130. catch (Exception e)
  131. {
  132. Console.WriteLine(e.ToString());
  133. }
  134. }
  135. public static int Main(String[] args)
  136. {
  137. StartListening();
  138. return 0;
  139. }
  140. }