当前位置:   article > 正文

c# TcP 开发

c# TcP 开发

在C#中进行TCP开发,通常使用System.Net.Sockets命名空间下的TcpListenerTcpClient类。以下是一个简单的TCP服务器和客户端示例。

TCP服务器端:

  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. class TcpServer
  6. {
  7. private TcpListener tcpListener;
  8. private int port;
  9. public TcpServer(int port)
  10. {
  11. this.port = port;
  12. }
  13. public void StartServer()
  14. {
  15. tcpListener = new TcpListener(IPAddress.Any, port);
  16. tcpListener.Start();
  17. Console.WriteLine($"Server started on port {port}.");
  18. while (true)
  19. {
  20. TcpClient client = tcpListener.AcceptTcpClient();
  21. HandleClient(client);
  22. }
  23. }
  24. private void HandleClient(TcpClient client)
  25. {
  26. NetworkStream stream = client.GetStream();
  27. byte[] bytes = Encoding.UTF8.GetBytes("Hello from the server!");
  28. stream.Write(bytes, 0, bytes.Length);
  29. stream.Close();
  30. client.Close();
  31. }
  32. }
  33. class Program
  34. {
  35. static void Main(string[] args)
  36. {
  37. TcpServer server = new TcpServer(8000);
  38. server.StartServer();
  39. }
  40. }

TCP客户端:

  1. using System;
  2. using System.IO;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. class TcpClient
  6. {
  7. private TcpClient tcpClient;
  8. private NetworkStream stream;
  9. private int port;
  10. private string host;
  11. public TcpClient(string host, int port)
  12. {
  13. this.host = host;
  14. this.port = port;
  15. }
  16. public void Connect()
  17. {
  18. tcpClient = new TcpClient(host, port);
  19. stream = tcpClient.GetStream();
  20. Console.WriteLine("Connected to server.");
  21. string response = GetResponse();
  22. Console.WriteLine($"Response from server: {response}");
  23. tcpClient.Close();
  24. }
  25. private string GetResponse()
  26. {
  27. byte[] bytes = new byte[1024];
  28. int bytesRead = stream.Read(bytes, 0, bytes.Length);
  29. return Encoding.UTF8.GetString(bytes, 0, bytesRead);
  30. }
  31. }
  32. class Program
  33. {
  34. static void Main(string[] args)
  35. {
  36. TcpClient client = new TcpClient("localhost", 8000);
  37. client.Connect();
  38. }
  39. }

在这个例子中,服务器监听8000端口,并接受任何客户端的连接。客户端连接到本机的8000端口,并接收来自服务器的问候消息。

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

闽ICP备14008679号