wxr
2022-08-17 d6578b10542226650e263815dea75e598a7090f9
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using HDL_ON.Entity;
using Newtonsoft.Json;
 
namespace HDL_ON.DriverLayer
{
    public class Control_TcpClient
    {
 
        //声明IP,端口,和一个用来连接的Socket
        public string _ip;
 
        private TcpClient _tcpClient;
 
        //创建一个委托,用来满足其他类调用
        //public delegate void DelegateMessage(string str);
        public Action<string> ReceiveEvent;
 
        /// <summary>
        /// 连接次数
        /// </summary>
        private int reconnectIndex = 0;
        /// <summary>
        /// 是否连接成功
        /// </summary>
        public bool isConnected = false;
 
 
        /// <summary>
        /// 构造函数
        /// </summary>
        public Control_TcpClient(string serverIp)
        {
            _ip = serverIp;
        }
 
        //TCP连接
        private bool ConnectToTcp( )
        {
            if (string.IsNullOrEmpty(_ip) )
            {
                return false;
            }
            if (_tcpClient == null)
            {
                _tcpClient = new TcpClient();
            }
            try
            {
                _tcpClient.Connect(IPAddress.Parse(_ip), 8586);
                Task.Run(new Action(ReceiveMessage));//开启线程,不停接收消息
                MainPage.Log($"打开tcp client{_ip}:8586");
                isConnected = true;
            }
            catch (Exception e)
            {
                MainPage.Log(e.Message);
                throw;
            }
            return true;//返回连接状态
        }
        /// <summary>
        /// 连接tcp线程
        /// </summary>
        private Thread connectThread;
 
        /// <summary>
        /// 连接线程
        /// </summary>
        public void Connect()
        {
            if(connectThread == null)
            {
                connectThread = new Thread(() => {
                    while (Control.Ins.GatewayOnline_Local)
                    {
                        if (_tcpClient == null)
                        {
                            ConnectToTcp();
                        }
                        else
                        {
                            if (!_tcpClient.Connected)
                            {
                                try
                                {
                                    //_tcpClient.ReceiveTimeout = 
                                    _tcpClient.Connect(IPAddress.Parse(_ip), 8586);
                                    Task.Run(new Action(ReceiveMessage));//开启线程,不停接收消息
                                }
                                catch (Exception ex)
                                {
                                    MainPage.Log($"tcp重连异常:{ex.Message}");
                                    _tcpClient.Close();
                                    _tcpClient = null;
                                }
                            }
                        }
                        Thread.Sleep(1000);
 
 
                    }
                });
                connectThread.Start();
            }
        }
 
 
        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <returns></returns>
        public bool Close()
        {
            if (_tcpClient == null)
                return true;
            _tcpClient.Close();
            _tcpClient = null;
            return true;
        }
 
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="bytes">需要发送的字节</param>
        public void SendMessage(byte[] bytes)
        {
            if (_tcpClient.GetStream().CanWrite)
            {
                _tcpClient.GetStream().Write(bytes, 0, bytes.Length);
            }
        }
        /// <summary>
        /// 心跳包线程
        /// </summary>
        private Thread heartBeatThread;
        private DateTime heartBeatTime;
        public void HeartBeat()
        {
            if(heartBeatThread == null)
            {
                heartBeatThread = new Thread(() => {
                    if(_tcpClient.Connected&&10 *1000 <(System.DateTime.Now - heartBeatTime).TotalMilliseconds)
                    {
                        var sendBytes = Control.Ins.ConvertSendBodyData(CommunicationTopic.ct.HeartBeat, "");
                        SendMessage(sendBytes);
                    }
                    Thread.Sleep(100);
                });
                heartBeatThread.Start();
            }
        }
        /// <summary>
        /// 接收数据线程
        /// </summary>
        private Thread receiveThread;
 
        //接收消息
        public void ReceiveMessage()
        {
            if(receiveThread == null)
            {
                receiveThread = new Thread(() => {
                    while (true)
                    {
                        if(_tcpClient == null)
                        {
                            receiveThread.Abort();
                            receiveThread = null;
                            return;
                        }
                        if (!_tcpClient.Connected)
                        {
                            MainPage.Log("tcp客户端断开了连接...");
                            receiveThread.Abort();
                            receiveThread = null;
                            isConnected = false;
                            return;
                        }
 
                        // 定义一个2M的缓存区;
                        byte[] arrMsgRec = new byte[1024 * 1024 * 2];
                        int size = _tcpClient.GetStream().Read(arrMsgRec, 0, arrMsgRec.Length);
                        var tcpDataString = System.Text.Encoding.UTF8.GetString(arrMsgRec, 0, arrMsgRec.Length);
 
 
                        if (!string.IsNullOrEmpty(tcpDataString))
                        {
                            MainPage.Log($"局域网tcp数据接收");
                            Control.Ins.ConvertReceiveData(arrMsgRec, null);
 
                        }
                    }
 
                });
                //receiveThread.IsBackground = true;
                receiveThread.Start();
            }
        }
 
 
    }
}