chunxiaqiu
2026-03-18 46431fb658701489f8d5de4475b02df728c51f36
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
 
namespace LB_VisionProcesses.Communicators.TCom
{
    [JsonObject(MemberSerialization.OptOut)]
    public class TCPClient : BaseCommunicator
    {
        private TcpClient _tcpClient = new TcpClient();
        private NetworkStream _networkStream;
        private StreamReader _reader;
        private StreamWriter _writer;
 
        public TCPClient(string name = "TCP客户端")
        {
            CommunicatorConnections.Add("地址", "127.0.0.1");
            CommunicatorConnections.Add("端口", "1111");
            CommunicatorBrand = CommunicatorBrand.TCPClient;
            CommunicatorName = name;
        }
 
        public override bool Connect()
        {
            try
            {
                Disconnect();
 
                int PORT = 0;
                if (!int.TryParse(this.CommunicatorConnections["端口"].ToString(), out PORT))
                {
                    Msg = string.Format("端口未设置");
                    return false;
                }
                if (!CommunicatorConnections.Contains("地址"))
                {
                    Msg = string.Format("地址未设置");
                    return false;
                }
                string IP = CommunicatorConnections["地址"].ToString();
 
                _tcpClient.Connect(IPAddress.Parse(IP), PORT);
                _networkStream = _tcpClient.GetStream();
                _reader = new StreamReader(_networkStream, Encoding.UTF8);
                //_writer = new StreamWriter(_networkStream, Encoding.UTF8) { AutoFlush = true };
                _writer = new StreamWriter(_networkStream, Encoding.UTF8) { AutoFlush = true };
                bConnected = true;
                bHeart = true;
 
                // 启动心跳线程
                heartbeatThread = new Thread(SendHeartbeat);
                heartbeatThread.IsBackground = true;
                heartbeatThread.Start();
 
                // 启动接收线程
                Task.Run(HandleServerComm);
                return true;
            }
            catch (Exception ex)
            {
                Msg = $"失败,服务器未启动: {ex.Message}";
                return false;
            }
        }
 
        public override bool Disconnect()
        {
            try
            {
                bConnected = false;
                if (_tcpClient.Connected)
                {
                    _reader.Close();
                    _writer.Close();
                    _networkStream.Close();
                    _tcpClient.Close();
                }
                _tcpClient = new TcpClient();
                return true;
            }
            catch
            {
                bConnected = false;
                return true;
            }
        }
 
        private async Task HandleServerComm()
        {
            while (bConnected)
            {
                try
                {
                    await Task.Delay(25); // 等待 25ms 后再尝试检查数据
 
                    byte[] buffer = new byte[1024];
                    int bytesRead = _networkStream.Read(buffer, 0, buffer.Length);
                    if (bytesRead > 0)
                    {
                        string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                        if (message != null)
                        {
                            strReceiveMsg = message;
                            try
                            {
                                TriggerRunMessageReceived?.Invoke(CommunicatorName, strReceiveMsg);  // 触发运行事件
                            }
                            catch { }
                            try
                            {
                                MessageReceived?.Invoke(strReceiveMsg); // 触发回调
                            }
                            catch { }
                        }
                    }
                }
                catch (Exception ex)
                {
                    bHeart = false;
                    Debug.WriteLine($"接收消息时发生错误: {ex.Message}");
                }
            }
        }
 
        // 发送消息到服务器
        public override bool SendMessage(string message)
        {
            if (!bConnected)
            {
                Msg = "尚未连接到服务器";
                return false;
            }
 
            try
            {
                //空消息不发送
                if (string.IsNullOrEmpty(message) || message.Trim() == "")
                    return true;
                _writer.Write(message);
                //_writer.Flush();  // 强制将缓冲区中的数据写入网络流
                return true;
            }
            catch (Exception ex)
            {
                bHeart = false;
                Msg = $"发送消息时发生错误: {ex.Message}";
                return false;
            }
        }
    }
}