当前位置:   article > 正文

C#网络通信实战:从零打造高性能Socket编程与TCP/IP协议栈应用_c# socket

c# socket

网络通信是现代软件开发中不可或缺的一部分,特别是在分布式系统和互联网应用中。C#提供了丰富的网络编程接口,尤其是基于Socket的TCP/IP协议栈编程,可以实现高性能的网络通信。以下从零开始逐步介绍如何在C#中使用Socket进行高性能网络通信编程,包括创建Socket、连接服务器、发送和接收数据,以及处理并发和错误等,包含详细的代码和注释。   

一、创建Socket

 

Csharp

  1. using System.Net;
  2. using System.Net.Sockets;
  3. public class NetworkClient
  4. {
  5. private Socket _clientSocket;
  6. public void Initialize(string serverAddress, int serverPort)
  7. {
  8. // 创建Socket实例
  9. _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  10. // 解析服务器地址
  11. IPAddress serverIp = IPAddress.Parse(serverAddress);
  12. // 创建终结点
  13. IPEndPoint serverEndPoint = new IPEndPoint(serverIp, serverPort);
  14. // 连接到服务器
  15. ConnectToServer(serverEndPoint);
  16. }
  17. private void ConnectToServer(IPEndPoint endPoint)
  18. {
  19. try
  20. {
  21. _clientSocket.Connect(endPoint);
  22. Console.WriteLine("Connected to server.");
  23. }
  24. catch (SocketException e)
  25. {
  26. Console.WriteLine($"Failed to connect: {e.Message}");
  27. Dispose();
  28. }
  29. }
  30. // 其他方法...
  31. }

二、发送数据

 

Csharp

  1. public void Send(byte[] data)
  2. {
  3. if (_clientSocket.Connected)
  4. {
  5. try
  6. {
  7. // 发送数据
  8. int bytesSent = _clientSocket.Send(data);
  9. Console.WriteLine($"Sent {bytesSent} bytes.");
  10. }
  11. catch (SocketException e)
  12. {
  13. Console.WriteLine($"Error sending data: {e.Message}");
  14. Dispose();
  15. }
  16. }
  17. else
  18. {
  19. Console.WriteLine("Not connected to server.");
  20. }
  21. }

三、接收数据

 

Csharp

  1. public byte[] Receive(int bufferSize)
  2. {
  3. byte[] receivedData = new byte[bufferSize];
  4. if (_clientSocket.Connected)
  5. {
  6. try
  7. {
  8. // 接收数据
  9. int bytesReceived = _clientSocket.Receive(receivedData);
  10. Console.WriteLine($"Received {bytesReceived} bytes.");
  11. Array.Resize(ref receivedData, bytesReceived);
  12. return receivedData;
  13. }
  14. catch (SocketException e)
  15. {
  16. Console.WriteLine($"Error receiving data: {e.Message}");
  17. Dispose();
  18. return null;
  19. }
  20. }
  21. else
  22. {
  23. Console.WriteLine("Not connected to server.");
  24. return null;
  25. }
  26. }

四、处理并发与错误

1. 异步编程

 

Csharp

  1. public async Task SendAsync(byte[] data)
  2. {
  3. if (_clientSocket.Connected)
  4. {
  5. try
  6. {
  7. await _clientSocket.SendAsync(new ArraySegment<byte>(data), SocketFlags.None);
  8. Console.WriteLine("Data sent asynchronously.");
  9. }
  10. catch (SocketException e)
  11. {
  12. Console.WriteLine($"Error sending data: {e.Message}");
  13. Dispose();
  14. }
  15. }
  16. else
  17. {
  18. Console.WriteLine("Not connected to server.");
  19. }
  20. }
  21. public async Task<byte[]> ReceiveAsync(int bufferSize)
  22. {
  23. byte[] receivedData = new byte[bufferSize];
  24. if (_clientSocket.Connected)
  25. {
  26. try
  27. {
  28. var result = await _clientSocket.ReceiveAsync(new ArraySegment<byte>(receivedData), SocketFlags.None);
  29. Console.WriteLine($"Received {result.ReceivedBytes} bytes asynchronously.");
  30. Array.Resize(ref receivedData, result.ReceivedBytes);
  31. return receivedData;
  32. }
  33. catch (SocketException e)
  34. {
  35. Console.WriteLine($"Error receiving data: {e.Message}");
  36. Dispose();
  37. return null;
  38. }
  39. }
  40. else
  41. {
  42. Console.WriteLine("Not connected to server.");
  43. return null;
  44. }
  45. }

2. 错误处理与重连

 

Csharp

  1. private void HandleSocketError(SocketError error)
  2. {
  3. switch (error)
  4. {
  5. case SocketError.ConnectionAborted:
  6. case SocketError.ConnectionReset:
  7. case SocketError.NetworkUnreachable:
  8. Console.WriteLine($"Disconnected from server: {error}");
  9. Reconnect();
  10. break;
  11. default:
  12. Console.WriteLine($"Unknown error: {error}");
  13. Dispose();
  14. break;
  15. }
  16. }
  17. private async Task Reconnect()
  18. {
  19. // 在此处实现重连逻辑,如等待一段时间后重新尝试连接服务器
  20. await Task.Delay(5000);
  21. ConnectToServer(_serverEndPoint);
  22. }

五、总结

C#中的Socket编程为开发者提供了直接访问TCP/IP协议栈的能力,可以实现高效的网络通信。通过创建Socket实例、连接服务器、发送和接收数据,以及处理并发和错误,可以构建稳定、高性能的网络客户端。同时,利用异步编程模型和适当的错误处理机制,可以进一步提升网络通信的性能和可靠性。以上示例代码展示了从零开始实现C# Socket编程的关键步骤和细节,为实际项目中的网络通信开发奠定了基础。

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/872320
推荐阅读
  

闽ICP备14008679号