溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C#中怎么利用Socket實(shí)現(xiàn)異步通訊

發(fā)布時(shí)間:2021-07-20 11:01:56 來(lái)源:億速云 閱讀:308 作者:Leah 欄目:編程語(yǔ)言

這篇文章將為大家詳細(xì)講解有關(guān)C#中怎么利用Socket實(shí)現(xiàn)異步通訊,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

C# Socket異步通訊客戶端之主程序:

  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() {
    // Connect to a remote device.

  30.  

  31. try {// Establish the remote endpoint for the socket.
    // The name of the
    // remote device is "host.contoso.com".
    IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); 

  32. // 生成一個(gè)TCP/IP socket.  

  33. Socket client = new Socket(AddressFamily.InterNetwork,  

  34. SocketType.Stream, ProtocolType.Tcp);  

  35.  

  36. // 與目標(biāo)終端連接.  

  37. client.BeginConnect(remoteEP,  

  38. new AsyncCallback(ConnectCallback), client);  

  39. //等待,直到連接程序完成。在ConnectCallback中適當(dāng)位置有connecDone.Set()語(yǔ)句  

  40. connectDone.WaitOne();  

  41.  

  42. // 發(fā)送數(shù)據(jù)到遠(yuǎn)程終端.  

  43. Send(client, "This is a test<EOF>");  

  44. sendDone.WaitOne();  

  45.  

  46. // 接收返回?cái)?shù)據(jù).  

  47. Receive(client);  

  48. receiveDone.WaitOne();  

  49.  

  50. // Write the response to the console.  

  51. Console.WriteLine("Response received : {0}", response);  

  52.  

  53. // Release the socket.  

  54. client.Shutdown(SocketShutdown.Both);  

  55. client.Close();  

  56. return 0;  

C# Socket異步通訊客戶端之連接部分Callback:

  1. private static void ConnectCallback(IAsyncResult ar)  

  2. {  

  3.  

  4. // 從state對(duì)象獲取socket.  

  5. Socket client = (Socket)ar.AsyncState;  

  6.  

  7. // 完成連接.  

  8. client.EndConnect(ar);  

  9.  

  10. Console.WriteLine("Socket connected to {0}",  

  11. client.RemoteEndPoint.ToString());  

  12.  

  13. // 連接已完成,主線程繼續(xù).  

  14. connectDone.Set();

  15. } catch (Exception e) {

  16. Console.WriteLine(e.ToString());

  17. }

  18. }

C# Socket異步通訊客戶端之?dāng)?shù)據(jù)接收:

  1.    private static void Receive(Socket client)  

  2. try {{  

  3.  

  4. // 構(gòu)造容器state.  

  5. StateObject state = new StateObject();  

  6. state.workSocket = client;  

  7.  

  8. // 從遠(yuǎn)程目標(biāo)接收數(shù)據(jù).  

  9. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,  

  10. new AsyncCallback(ReceiveCallback), state);  

  11. } catch (Exception e) {

  12. Console.WriteLine(e.ToString());

  13. }
    }

  14.  

  15. private static void ReceiveCallback(IAsyncResult ar)  

  16. {  

  17.  

  18. // 從輸入?yún)?shù)異步state對(duì)象中獲取state和socket對(duì)象  

  19. StateObject state = (StateObject)ar.AsyncState;  

  20. Socket client = state.workSocket;  

  21.  

  22. //從遠(yuǎn)程設(shè)備讀取數(shù)據(jù)  

  23. int bytesRead = client.EndReceive(ar);  

  24.  

  25. if (bytesRead > 0)  

  26. {  

  27. // 有數(shù)據(jù),存儲(chǔ).  

  28. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));  

  29.  

  30. // 繼續(xù)讀取.  

  31. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,  

  32. new AsyncCallback(ReceiveCallback), state);  

  33. }  

  34. else 

  35. {  

  36. // 所有數(shù)據(jù)讀取完畢.  

  37. if (state.sb.Length > 1)  

  38. {  

  39. response = state.sb.ToString();  

  40. }  

  41. // 所有數(shù)據(jù)讀取完畢的指示信號(hào).  

  42. receiveDone.Set();  

  43. }  

  44. } catch (Exception e) {

  45. Console.WriteLine(e.ToString());

  46. }

  47. }

C# Socket異步通訊客戶端之發(fā)送數(shù)據(jù):

  1. private static void Send(Socket client, String data)  

  2. {  

  3. // 格式轉(zhuǎn)換.  

  4. byte[] byteData = Encoding.ASCII.GetBytes(data);  

  5.  

  6. // 開(kāi)始發(fā)送數(shù)據(jù)到遠(yuǎn)程設(shè)備.  

  7. client.BeginSend(byteData, 0, byteData.Length, 0,  

  8. new AsyncCallback(SendCallback), client);  

  9. }   

  10. private static void SendCallback(IAsyncResult ar)  

  11. {  

  12.  

  13. // 從state對(duì)象中獲取socket  

  14. Socket client = (Socket)ar.AsyncState;  

  15.  

  16. // 完成數(shù)據(jù)發(fā)送.  

  17. int bytesSent = client.EndSend(ar);  

  18. Console.WriteLine("Sent {0} bytes to server.", bytesSent);  

  19.  

  20. // 指示數(shù)據(jù)已經(jīng)發(fā)送完成,主線程繼續(xù).  

  21. sendDone.Set();  

  22. } catch (Exception e) {

  23. Console.WriteLine(e.ToString());

  24. }


  25. }

  26. public static int Main(String[] args) {

  27. StartClient();

  28. return 0;

  29. }

  30. }

關(guān)于C#中怎么利用Socket實(shí)現(xiàn)異步通訊就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI