日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
淺析C#異步套接字的實(shí)現(xiàn)過程

C#異步套接字實(shí)現(xiàn)是如何的呢?讓我們開始從實(shí)例開始:

創(chuàng)新互聯(lián)公司-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比平昌網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫(kù),直接使用。一站式平昌網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋平昌地區(qū)。費(fèi)用合理售后完善,10余年實(shí)體公司更值得信賴。

下面的C#異步套接字實(shí)現(xiàn)實(shí)例程序創(chuàng)建一個(gè)連接到服務(wù)器的客戶端。該客戶端是用C#異步套接字生成的,因此在等待服務(wù)器返回響應(yīng)時(shí)不掛起客戶端應(yīng)用程序的執(zhí)行。該應(yīng)用程序?qū)⒆址l(fā)送到服務(wù)器,然后在控制臺(tái)顯示該服務(wù)器返回的字符串。

 
 
 
  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.     
  97. state.sb.Append(Encoding.ASCII.GetString(      
  98. state.buffer,0,bytesRead));       
  99. // Get the rest of the data.       
  100. client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,       
  101. new AsyncCallback(ReceiveCallback), state);       
  102. } else {       
  103. // All the data has arrived; put it in response.       
  104. if (state.sb.Length > 1) {       
  105. response = state.sb.ToString();       
  106. }       
  107. // Signal that all bytes have been received.       
  108. receiveDone.Set();       
  109. }       
  110. } catch (Exception e) {       
  111. Console.WriteLine(e.ToString());       
  112. }       
  113. }       
  114. private static void Send(Socket client, String data) {       
  115. // Convert the string data to byte data using ASCII encoding.       
  116. byte[] byteData = Encoding.ASCII.GetBytes(data);       
  117. // Begin sending the data to the remote device.       
  118. client.BeginSend(byteData, 0, byteData.Length, 0,       
  119. new AsyncCallback(SendCallback), client);       
  120. }       
  121. private static void SendCallback(IAsyncResult ar) {       
  122. try {       
  123. // Retrieve the socket from the state object.       
  124. Socket client = (Socket) ar.AsyncState;       
  125. // Complete sending the data to the remote device.       
  126. int bytesSent = client.EndSend(ar);       
  127. Console.WriteLine("Sent {0} bytes to server.", bytesSent);       
  128. // Signal that all bytes have been sent.       
  129. sendDone.Set();       
  130. } catch (Exception e) {       
  131. Console.WriteLine(e.ToString());       
  132. }       
  133. }       
  134. public static int Main(String[] args) {       
  135. StartClient();       
  136. return 0;       
  137. }       
  138. }    

C#異步套接字在服務(wù)器的示例 下面的示例程序創(chuàng)建一個(gè)接收來(lái)自客戶端的連接請(qǐng)求的服務(wù)器。該服務(wù)器是用C#異步套接字生成的

因此在等待來(lái)自客戶端的連接時(shí)不掛起服務(wù)器應(yīng)用程序的執(zhí)行。該應(yīng)用程序接收來(lái)自客戶端的字符串

在控制臺(tái)顯示該字符串,然后將該字符串回顯到客戶端。來(lái)自客戶端的字符串必須包含字符串“”

以發(fā)出表示消息結(jié)尾的信號(hào)。

 
 
 
  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. }       
  17. public class AsynchronousSocketListener {       
  18. // Thread signal.       
  19. public static ManualResetEvent allDone =       
  20. new ManualResetEvent(false);       
  21. public AsynchronousSocketListener() {       
  22. }       
  23. public static void StartListening() {       
  24. // Data buffer for incoming data.       
  25. byte[] bytes = new Byte[1024];       
  26. // Establish the local endpoint for the socket.       
  27. // The DNS name of the computer       
  28. // running the listener is "host.contoso.com".       
  29. IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());       
  30. IPAddress ipAddress = ipHostInfo.AddressList[0];       
  31. IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);       
  32. // Create a TCP/IP socket.       
  33. Socket listener = new Socket(AddressFamily.InterNetwork,       
  34. SocketType.Stream, ProtocolType.Tcp );       
  35. // Bind the socket to the local       
  36. //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,       
  67. 0, StateObject.BufferSize, 0,       
  68. new AsyncCallback(ReadCallback), state);       
  69. }       
  70. public static void ReadCallback(IAsyncResult ar) {       
  71. String content = String.Empty;       
  72. // Retrieve the state object and the handler socket       
  73. // from the asynchronous state object.       
  74. StateObject state = (StateObject) ar.AsyncState;       
  75. Socket handler = state.workSocket;       
  76. // Read data from the client socket.       
  77. int bytesRead = handler.EndReceive(ar);       
  78. if (bytesRead > 0) {       
  79. // There might be more data, so store the data received so far.       
  80. state.sb.Append(Encoding.ASCII.GetString(       
  81. state.buffer,0,bytesRead));       
  82. // Check for end-of-file tag. If it is not there, read       
  83. // more data.       
  84. content = state.sb.ToString();       
  85. if (content.IndexOf("< EOF>") > -1) {       
  86. // All the data has been read from the       
  87. // client. Display it on the console.       
  88. Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",       
  89. content.Length, content );       
  90. // Echo the data back to the client.       
  91. Send(handler, content);       
  92. } else {       
  93. // Not all data received. Get more.       
  94. handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,       
  95. new AsyncCallback(ReadCallback), state);       
  96. }       
  97. }       
  98. }       
  99. private static void Send(Socket handler, String data) {       
  100. // Convert the string data to byte data using ASCII encoding.       
  101. byte[] byteData = Encoding.ASCII.GetBytes(data);       
  102. // Begin sending the data to the remote device.       
  103. handler.BeginSend(byteData, 0, byteData.Length, 0,       
  104. new AsyncCallback(SendCallback), handler);       
  105. }       
  106. private static void SendCallback(IAsyncResult ar) {       
  107. try {       
  108. // Retrieve the socket from the state object.       
  109. Socket handler = (Socket) ar.AsyncState;       
  110. // Complete sending the data to the remote device.       
  111. int bytesSent = handler.EndSend(ar);       
  112. Console.WriteLine("Sent {0} bytes to client.", bytesSent);       
  113. handler.Shutdown(SocketShutdown.Both);       
  114. handler.Close();       
  115. } catch (Exception e) {       
  116. Console.WriteLine(e.ToString());       
  117. }       
  118. }       
  119. public static int Main(String[] args) {       
  120. StartListening();       
  121. return 0;       
  122. }       
  123. }    

C#異步套接字的相關(guān)內(nèi)容就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C#異步套接字有所幫助。

【編輯推薦】

  1. 總結(jié)C#語(yǔ)言命名規(guī)范
  2. C#反射相關(guān)知識(shí)學(xué)習(xí)
  3. 大話F#和C#:是否會(huì)重蹈C#失敗的覆轍?
  4. 總結(jié)和學(xué)習(xí)C#接口
  5. 學(xué)習(xí)C#程序有感

新聞標(biāo)題:淺析C#異步套接字的實(shí)現(xiàn)過程
URL網(wǎng)址:http://www.dlmjj.cn/article/djdccsh.html