TcpClientClass.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace TCPIPTest
  8. {
  9. internal class TcpClientClass
  10. {
  11. TcpClient client = null;
  12. NetworkStream stream = null;
  13. public bool CreatTcpClient(string serverIp, int port)
  14. {
  15. bool result = false;
  16. // 连接到服务器
  17. try
  18. {
  19. client = new TcpClient(serverIp, port);
  20. Console.WriteLine("已连接到服务器");
  21. stream = client.GetStream();
  22. result = true;
  23. }
  24. catch (Exception ex)
  25. {
  26. Console.WriteLine($"Connect to server failed:{ex.Message}");
  27. }
  28. return result;
  29. }
  30. public void SendMessage(ushort message)
  31. {
  32. byte[] data = BitConverter.GetBytes(message);
  33. stream.Write(data, 0, data.Length);
  34. Console.WriteLine($"{DateTime.Now.ToString("O")}已发送消息: {message}");
  35. }
  36. public byte[] ReadMessage()
  37. {
  38. // 接收响应
  39. byte[] buffer = new byte[256];
  40. int bytesRead = stream.Read(buffer, 0, buffer.Length);
  41. return buffer;
  42. }
  43. }
  44. }