C# Socket异步通讯实现详解

开发 后端
C# Socket异步通讯是如何实现的呢?C# Socket异步通讯客户端设计的思路是什么呢?那么本文就向你介绍具体的内容。

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异步通讯客户端的实现源码内容就基本向你介绍到这里,希望对你了解和学习C# Socket异步通讯有所帮助。

【编辑推荐】

  1. C#对象初始化学习总结
  2. C#改写方法学习笔记
  3. 概述C#加框和消框
  4. 浅析C#异步操作
  5. 描述C#异步Socket

 

责任编辑:仲衡 来源: 博客园
相关推荐

2009-08-03 16:45:02

C#异步Socket

2009-08-21 10:13:02

C#异步初步

2024-03-21 08:34:49

Vue3WebSocketHTTP

2010-03-18 17:23:55

Java Socket

2010-12-22 10:21:17

C#基础

2009-08-21 09:20:44

C#异步套接字

2009-08-21 11:39:58

C# Socket通信

2009-08-21 11:24:16

C#异步调用

2009-08-25 18:04:30

C#实现Singlet

2009-08-31 16:23:13

C#接口

2009-09-09 18:50:23

C# 加密RSA

2009-08-27 17:14:36

C# Socket

2024-10-15 08:29:09

C#软件开发

2009-08-18 16:45:40

C# Raw Sock

2009-09-09 18:57:26

C# 加密TripleDES

2009-08-25 17:43:17

C#串口监听

2009-08-25 10:44:50

C#实现多语言

2009-08-26 09:48:48

C#异步套接字

2009-08-26 11:07:36

C#打印窗体

2009-08-26 09:22:44

C#实现打印功能
点赞
收藏

51CTO技术栈公众号