虚位以待(AD)
虚位以待(AD)
首页 > 软件编程 > C#编程 > c#(Socket)异步套接字代码示例

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

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


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

 

相关热词搜索: c Socket 异步 套接字