C#Socket异步通讯实现详解

C# Socket异步通讯客户端实现源码

达拉特网站制作公司哪家好,找创新互联公司!从网页设计、网站建设、微信开发、APP开发、响应式网站等网站项目制作,到程序开发,运营维护。创新互联公司于2013年创立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联公司

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. 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);
  31. // 生成一个TCP/IP socket.
  32. Socket client = new Socket(AddressFamily.InterNetwork,
  33. SocketType.Stream, ProtocolType.Tcp);
  34. // 与目标终端连接.
  35. client.BeginConnect(remoteEP,
  36. new AsyncCallback(ConnectCallback), client);
  37. //等待,直到连接程序完成。在ConnectCallback中适当位置有connecDone.Set()语句
  38. connectDone.WaitOne();
  39. // 发送数据到远程终端.
  40. Send(client, "This is a test");
  41. sendDone.WaitOne();
  42. // 接收返回数据.
  43. Receive(client);
  44. receiveDone.WaitOne();
  45. // Write the response to the console.
  46. Console.WriteLine("Response received : {0}", response);
  47. // Release the socket.
  48. client.Shutdown(SocketShutdown.Both);
  49. client.Close();
  50. return 0;
  51. }

C# Socket异步通讯客户端之连接部分Callback:

 
 
 
  1. private static void ConnectCallback(IAsyncResult ar)
  2. {
  3. // 从state对象获取socket.
  4. Socket client = (Socket)ar.AsyncState;
  5. // 完成连接.
  6. client.EndConnect(ar);
  7. Console.WriteLine("Socket connected to {0}",
  8. client.RemoteEndPoint.ToString());
  9. // 连接已完成,主线程继续.
  10. connectDone.Set();
  11. } catch (Exception e) {
  12. Console.WriteLine(e.ToString());
  13. }
  14. }

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

 
 
 
  1.    private static void Receive(Socket client)
  2. try {{
  3. // 构造容器state.
  4. StateObject state = new StateObject();
  5. state.workSocket = client;
  6. // 从远程目标接收数据.
  7. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  8. new AsyncCallback(ReceiveCallback), state);
  9. } catch (Exception e) {
  10. Console.WriteLine(e.ToString());
  11. }
    }
  12. private static void ReceiveCallback(IAsyncResult ar)
  13. {
  14. // 从输入参数异步state对象中获取state和socket对象
  15. StateObject state = (StateObject)ar.AsyncState;
  16. Socket client = state.workSocket;
  17. //从远程设备读取数据
  18. int bytesRead = client.EndReceive(ar);
  19. if (bytesRead > 0)
  20. {
  21. // 有数据,存储.
  22. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
  23. // 继续读取.
  24. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  25. new AsyncCallback(ReceiveCallback), state);
  26. }
  27. else
  28. {
  29. // 所有数据读取完毕.
  30. if (state.sb.Length > 1)
  31. {
  32. response = state.sb.ToString();
  33. }
  34. // 所有数据读取完毕的指示信号.
  35. receiveDone.Set();
  36. }
  37. } catch (Exception e) {
  38. Console.WriteLine(e.ToString());
  39. }
  40. }

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

 
 
 
  1. private static void Send(Socket client, String data)
  2. {
  3. // 格式转换.
  4. byte[] byteData = Encoding.ASCII.GetBytes(data);
  5. // 开始发送数据到远程设备.
  6. client.BeginSend(byteData, 0, byteData.Length, 0,
  7. new AsyncCallback(SendCallback), client);
  8. }  
  9. private static void SendCallback(IAsyncResult ar)
  10. {
  11. // 从state对象中获取socket
  12. Socket client = (Socket)ar.AsyncState;
  13. // 完成数据发送.
  14. int bytesSent = client.EndSend(ar);
  15. Console.WriteLine("Sent {0} bytes to server.", bytesSent);
  16. // 指示数据已经发送完成,主线程继续.
  17. sendDone.Set();
  18. }
  19. } catch (Exception e) {
  20. Console.WriteLine(e.ToString());
  21. }

  22. }
  23. public static int Main(String[] args) {
  24. StartClient();
  25. return 0;
  26. }
  27. }

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

文章名称:C#Socket异步通讯实现详解
标题来源:http://www.shufengxianlan.com/qtweb/news10/60960.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联