A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈君 金牌黑马   /  2014-8-10 17:25  /  1070 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

异步客户端套接字示例


下面的示例程序创建一个连接到服务器的客户端。该客户端是用异步套接字生成的,因此在等待服务器返回响应时不挂起客户端应用程序的执行。该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串。

C#
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Threading;
  5. using System.Text;
  6. // State object for receiving data from remote device.
  7. public class StateObject {
  8. // Client socket.
  9. public Socket workSocket = null;
  10. // Size of receive buffer.
  11. public const int BufferSize = 256;
  12. // Receive buffer.
  13. public byte[] buffer = new byte[BufferSize];
  14. // Received data string.
  15. public StringBuilder sb = new StringBuilder();
  16. }
  17. public class AsynchronousClient {
  18. // The port number for the remote device.
  19. private const int port = 11000;
  20. // ManualResetEvent instances signal completion.
  21. private static ManualResetEvent connectDone =
  22. new ManualResetEvent(false);
  23. private static ManualResetEvent sendDone =
  24. new ManualResetEvent(false);
  25. private static ManualResetEvent receiveDone =
  26. new ManualResetEvent(false);
  27. // The response from the remote device.
  28. private static String response = String.Empty;
  29. private static void StartClient() {
  30. // Connect to a remote device.
  31. try {
  32. // Establish the remote endpoint for the socket.
  33. // The name of the
  34. // remote device is "host.contoso.com".
  35. IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
  36. IPAddress ipAddress = ipHostInfo.AddressList[0];
  37. IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
  38. // Create a TCP/IP socket.
  39. Socket client = new Socket(AddressFamily.InterNetwork,
  40. SocketType.Stream, ProtocolType.Tcp);
  41. // Connect to the remote endpoint.
  42. client.BeginConnect( remoteEP,
  43. new AsyncCallback(ConnectCallback), client);
  44. connectDone.WaitOne();
  45. // Send test data to the remote device.
  46. Send(client,"This is a test<EOF>");
  47. sendDone.WaitOne();
  48. // Receive the response from the remote device.
  49. Receive(client);
  50. receiveDone.WaitOne();
  51. // Write the response to the console.
  52. Console.WriteLine("Response received : {0}", response);
  53. // Release the socket.
  54. client.Shutdown(SocketShutdown.Both);
  55. client.Close();
  56. } catch (Exception e) {
  57. Console.WriteLine(e.ToString());
  58. }
  59. }
  60. private static void ConnectCallback(IAsyncResult ar) {
  61. try {
  62. // Retrieve the socket from the state object.
  63. Socket client = (Socket) ar.AsyncState;
  64. // Complete the connection.
  65. client.EndConnect(ar);
  66. Console.WriteLine("Socket connected to {0}",
  67. client.RemoteEndPoint.ToString());
  68. // Signal that the connection has been made.
  69. connectDone.Set();
  70. } catch (Exception e) {
  71. Console.WriteLine(e.ToString());
  72. }
  73. }
  74. private static void Receive(Socket client) {
  75. try {
  76. // Create the state object.
  77. StateObject state = new StateObject();
  78. state.workSocket = client;
  79. // Begin receiving the data from the remote device.
  80. client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
  81. new AsyncCallback(ReceiveCallback), state);
  82. } catch (Exception e) {
  83. Console.WriteLine(e.ToString());
  84. }
  85. }
  86. private static void ReceiveCallback( IAsyncResult ar ) {
  87. try {
  88. // Retrieve the state object and the client socket
  89. // from the asynchronous state object.
  90. StateObject state = (StateObject) ar.AsyncState;
  91. Socket client = state.workSocket;
  92. // Read data from the remote device.
  93. int bytesRead = client.EndReceive(ar);
  94. if (bytesRead > 0) {
  95. // There might be more data, so store the data received so far.
  96. state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
  97. // Get the rest of the data.
  98. client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
  99. new AsyncCallback(ReceiveCallback), state);
  100. } else {
  101. // All the data has arrived; put it in response.
  102. if (state.sb.Length > 1) {
  103. response = state.sb.ToString();
  104. }
  105. // Signal that all bytes have been received.
  106. receiveDone.Set();
  107. }
  108. } catch (Exception e) {
  109. Console.WriteLine(e.ToString());
  110. }
  111. }
  112. private static void Send(Socket client, String data) {
  113. // Convert the string data to byte data using ASCII encoding.
  114. byte[] byteData = Encoding.ASCII.GetBytes(data);
  115. // Begin sending the data to the remote device.
  116. client.BeginSend(byteData, 0, byteData.Length, 0,
  117. new AsyncCallback(SendCallback), client);
  118. }
  119. private static void SendCallback(IAsyncResult ar) {
  120. try {
  121. // Retrieve the socket from the state object.
  122. Socket client = (Socket) ar.AsyncState;
  123. // Complete sending the data to the remote device.
  124. int bytesSent = client.EndSend(ar);
  125. Console.WriteLine("Sent {0} bytes to server.", bytesSent);
  126. // Signal that all bytes have been sent.
  127. sendDone.Set();
  128. } catch (Exception e) {
  129. Console.WriteLine(e.ToString());
  130. }
  131. }
  132. public static int Main(String[] args) {
  133. StartClient();
  134. return 0;
  135. }
  136. }
复制代码

异步服务器套接字示例 下面的示例程序创建一个接收来自客户端的连接请求的服务器。该服务器是用异步套接字生成的,
因此在等待来自客户端的连接时不挂起服务器应用程序的执行。该应用程序接收来自客户端的字符串,
在控制台显示该字符串,然后将该字符串回显到客户端。来自客户端的字符串必须包含字符串“<EOF>”,
以发出表示消息结尾的信号。
  1. C#
  2. 复制代码

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


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马