< 返回技术文档列表

C#中怎么利用Socket实现异步通讯

发布时间:2021-09-01 01:54:08⊙投诉举报

这篇文章将为大家详细讲解有关C#中怎么利用Socket实现异步通讯,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

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. // 生成一个TCP/IP socket.  

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

  34. SocketType.Stream, ProtocolType.Tcp);  

  35.  

  36. // 与目标终端连接.  

  37. client.BeginConnect(remoteEP,  

  38. new AsyncCallback(ConnectCallback), client);  

  39. //等待,直到连接程序完成。在ConnectCallback中适当位置有connecDone.Set()语句  

  40. connectDone.WaitOne();  

  41.  

  42. // 发送数据到远程终端.  

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

  44. sendDone.WaitOne();  

  45.  

  46. // 接收返回数据.  

  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对象获取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. // 连接已完成,主线程继续.  

  14. connectDone.Set();

  15. } catch (Exception e) {

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

  17. }

  18. }

C# Socket异步通讯客户端之数据接收:

  1.    private static void Receive(Socket client)  

  2. try {{  

  3.  

  4. // 构造容器state.  

  5. StateObject state = new StateObject();  

  6. state.workSocket = client;  

  7.  

  8. // 从远程目标接收数据.  

  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. // 从输入参数异步state对象中获取state和socket对象  

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

  20. Socket client = state.workSocket;  

  21.  

  22. //从远程设备读取数据  

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

  24.  

  25. if (bytesRead > 0)  

  26. {  

  27. // 有数据,存储.  

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

  29.  

  30. // 继续读取.  

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

  32. new AsyncCallback(ReceiveCallback), state);  

  33. }  

  34. else 

  35. {  

  36. // 所有数据读取完毕.  

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

  38. {  

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

  40. }  

  41. // 所有数据读取完毕的指示信号.  

  42. receiveDone.Set();  

  43. }  

  44. } catch (Exception e) {

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

  46. }

  47. }

C# Socket异步通讯客户端之发送数据:

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

  2. {  

  3. // 格式转换.  

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

  5.  

  6. // 开始发送数据到远程设备.  

  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对象中获取socket  

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

  15.  

  16. // 完成数据发送.  

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

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

  19.  

  20. // 指示数据已经发送完成,主线程继续.  

  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. }

关于C#中怎么利用Socket实现异步通讯就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


/template/Home/Zkeys/PC/Static