自动化立体仓库 - WCS系统
#
luxiaotao1123
2020-08-05 7e36eb78c63d2ed483bb8f717666f25c54f2e8b3
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
package com.zy.common.HslCommunication.Enthernet.ComplexNet;
 
import com.zy.common.HslCommunication.Core.Net.HslProtocol;
import com.zy.common.HslCommunication.Core.Net.NetHandle;
import com.zy.common.HslCommunication.Core.Net.NetworkBase.NetworkXBase;
import com.zy.common.HslCommunication.Core.Net.StateOne.AppSession;
import com.zy.common.HslCommunication.Core.Types.*;
import com.zy.common.HslCommunication.Utilities;
 
import java.net.Socket;
import java.util.Date;
 
/**
 * 一个基于异步高性能的客户端网络类,支持主动接收服务器的消息
 */
public class NetComplexClient extends NetworkXBase {
 
 
    /**
     * 实例化一个对象
     */
    public NetComplexClient() {
        session = new AppSession();
        ServerTime = new Date();
 
    }
 
 
    private AppSession session;                  // 客户端的核心连接对象
    private int isConnecting = 0;                // 指示客户端是否处于连接服务器中,0代表未连接,1代表连接中
    private boolean IsQuie = false;              // 指示系统是否准备退出
    private Thread thread_heart_check = null;   // 心跳线程
    private String ipAddress = "";               // Ip地址
    private int port = 1000;                     // 端口号
    private boolean IsClientStart = false;         // 客户端是否启动
    private int ConnectFailedCount = 0;            // 失败重连次数
    private String ClientAlias = "";             // 客户端的别名
    private Date ServerTime = new Date();        // 服务器的时间,暂时不支持使用
    private int DelayTime = 0;                   // 获取延迟的时间
 
    /**
     * 获取IP地址
     *
     * @return Ip地址
     */
    public String getIpAddress() {
        return ipAddress;
    }
 
    /**
     * 设置Ip地址
     *
     * @param ipAddress Ip地址
     */
    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }
 
    /**
     * 获取端口号
     *
     * @return 端口号
     */
    public int getPort() {
        return port;
    }
 
    /**
     * 设置端口号
     *
     * @param port
     */
    public void setPort(int port) {
        this.port = port;
    }
 
    /**
     * 获取客户端是否启动
     *
     * @return boolean值
     */
    public boolean getIsClientStart() {
        return IsClientStart;
    }
 
    /**
     * 设置客户端是否启动
     *
     * @param clientStart 客户端是否启动
     */
    public void setClientStart(boolean clientStart) {
        IsClientStart = clientStart;
    }
 
    /**
     * 获取失败重连次数
     *
     * @return
     */
    public int getConnectFailedCount() {
        return ConnectFailedCount;
    }
 
    /**
     * 获取客户端的登录标识名
     *
     * @return 字符串信息
     */
    public String getClientAlias() {
        return ClientAlias;
    }
 
    /**
     * 设置客户端的登录标识名
     *
     * @param clientAlias
     */
    public void setClientAlias(String clientAlias) {
        ClientAlias = clientAlias;
    }
 
 
    /**
     * 获取服务器的时间
     * @return
     */
//    public Date getServerTime() {
//        return ServerTime;
//    }
 
    /**
     * 获取信息延迟的时间
     *
     * @return
     */
    public int getDelayTime() {
        return DelayTime;
    }
 
 
    /**
     * 客户端启动成功的事件,重连成功也将触发此事件,参数没有意义
     */
    public ActionOperate LoginSuccess;
 
    /**
     * 连接失败时触发的事件,参数为连接失败的次数
     */
    public ActionOperateExOne<Integer> LoginFailed;
 
    /**
     * 服务器的异常,启动,等等一般消息产生的时候,出发此事件
     */
    public ActionOperateExOne<String> MessageAlerts;
 
    /**
     * 在客户端断开后并在重连服务器之前触发,用于清理系统资源,参数无意义
     */
    public ActionOperate BeforReConnected;
 
    /**
     * 当接收到文本数据的时候,触发此事件
     */
    public ActionOperateExThree<NetComplexClient, NetHandle, String> AcceptString;
 
    /**
     * 当接收到字节数据的时候,触发此事件
     */
    public ActionOperateExThree<NetComplexClient, NetHandle, byte[]> AcceptByte;
 
 
    /**
     * 关闭该客户端引擎
     */
    public void ClientClose() {
        IsQuie = true;
        if (IsClientStart)
            SendBytes(session, HslProtocol.CommandBytes(HslProtocol.ProtocolClientQuit, 0, Token, null));
 
        IsClientStart = false;          // 关闭客户端
        thread_heart_check = null;
 
        LoginSuccess = null;            // 清空所有的事件
        LoginFailed = null;
        MessageAlerts = null;
        AcceptByte = null;
        AcceptString = null;
        try {
            session.getWorkSocket().close();
        } catch (Exception ex) {
 
        }
        if (LogNet != null) LogNet.WriteDebug(toString(), "Client Close.");
    }
 
 
    /**
     * 启动客户端引擎,连接服务器系统
     */
    public void ClientStart() {
        // 如果处于连接中就退出
        if (isConnecting != 0) return;
        isConnecting = 1;
 
        // 启动后台线程连接
        new Thread(){
            @Override
            public void run() {
                ThreadLogin();
            }
        }.start();
 
        // 启动心跳线程,在第一次Start的时候
        if (thread_heart_check == null) {
            thread_heart_check = new Thread(){
                @Override
                public void run() {
                    ThreadHeartCheck();
                }
            };
            thread_heart_check.start();
        }
    }
 
    /**
     * 连接服务器之前的消息提示,如果是重连的话,就提示10秒等待信息
     */
    private void AwaitToConnect() {
        if (ConnectFailedCount == 0) {
            // English Version : Connecting Server...
            if (MessageAlerts != null) MessageAlerts.Action("正在连接服务器...");
        } else {
            int count = 10;
            while (count > 0) {
                if (IsQuie) return;
                count--;
                // English Version : Disconnected, wait [count] second to restart
                if (MessageAlerts != null) MessageAlerts.Action("连接断开,等待" + count + "秒后重新连接");
                try {
                    Thread.sleep(1000);
                } catch (Exception ex) {
 
                }
            }
            if (MessageAlerts != null) MessageAlerts.Action("正在尝试第" + ConnectFailedCount + "次连接服务器...");
        }
    }
 
    private void ConnectFailed() {
        ConnectFailedCount++;
        isConnecting = 0;
        if (LoginFailed != null) LoginFailed.Action(ConnectFailedCount);
        if (LogNet != null) LogNet.WriteDebug(toString(), "Connected Failed, Times: " + ConnectFailedCount);
    }
 
    private OperateResultExOne<Socket> ConnectServer() {
        OperateResultExOne<Socket> connectResult = CreateSocketAndConnect(ipAddress, port, 10000);
        if (!connectResult.IsSuccess) {
            return connectResult;
        }
 
        // 连接成功,发送数据信息
        OperateResult sendResult = SendStringAndCheckReceive(connectResult.Content, 2, ClientAlias);
        if (!sendResult.IsSuccess) {
            return OperateResultExOne.<Socket>CreateFailedResult(sendResult);
        }
 
        if (MessageAlerts != null) MessageAlerts.Action("连接服务器成功!");
        return connectResult;
    }
 
    private void LoginSuccessMethod(Socket socket) {
        ConnectFailedCount = 0;
        try {
            session.setIpEndPoint(socket.getInetAddress());
            session.setLoginAlias(ClientAlias);
            session.setWorkSocket(socket);
            session.setHeartTime(new Date());
            IsClientStart = true;
            BeginReceiveBackground(session);
        } catch (Exception ex) {
            if (LogNet != null) LogNet.WriteException(toString(), ex);
        }
    }
 
 
    private void ThreadLogin() {
        // 连接的消息等待
        AwaitToConnect();
 
        OperateResultExOne<Socket> connectResult = ConnectServer();
        if (!connectResult.IsSuccess) {
            ConnectFailed();
            // 连接失败,重新连接服务器
            new Thread(){
                @Override
                public void run() {
                    ReconnectServer(null);
                }
            }.start();
            return;
        }
 
        // 登录成功
        LoginSuccessMethod(connectResult.Content);
 
        // 登录成功
        if (LoginSuccess != null) LoginSuccess.Action();
        isConnecting = 0;
        try {
            Thread.sleep(200);
        } catch (Exception ex) {
 
        }
    }
 
 
    private void ReconnectServer(Object obj) {
        // 是否连接服务器中,已经在连接的话,则不再连接
        if (isConnecting == 1) return;
        // 是否退出了系统,退出则不再重连
        if (IsQuie) return;
        // 触发连接失败,重连系统前错误
        if (BeforReConnected != null) BeforReConnected.Action();
        if (session != null) {
            CloseSocket(session.getWorkSocket());
        }
        // 重新启动客户端
        ClientStart();
    }
 
 
    /**
     * 通信出错后的处理
     *
     * @param receive 通信方法
     */
    @Override
    protected void SocketReceiveException(AppSession receive) {
        if (LogNet != null) LogNet.WriteDebug(toString(), "Socket Excepiton Occured.");
        // 异常掉线
        ReconnectServer(null);
 
    }
 
 
    /**
     * 服务器端用于数据发送文本的方法
     *
     * @param customer 用户自定义的命令头
     * @param str      发送的文本
     */
    public void Send(NetHandle customer, String str) {
        if (IsClientStart) {
            SendBytes(session, HslProtocol.CommandBytes(customer.get_CodeValue(), Token, str));
        }
    }
 
 
    /**
     * 服务器端用于发送字节的方法
     *
     * @param customer 用户自定义的命令头
     * @param bytes    实际发送的数据
     */
    public void Send(NetHandle customer, byte[] bytes) {
        if (IsClientStart) {
            SendBytes(session, HslProtocol.CommandBytes(customer.get_CodeValue(), Token, bytes));
        }
    }
 
    private void SendBytes(AppSession stateone, byte[] content) {
        super.Send(stateone.getWorkSocket(), content);
    }
 
 
    /**
     * 客户端的数据处理中心
     *
     * @param session  连接状态
     * @param protocol 协议头
     * @param customer 用户自定义
     * @param content  数据内容
     */
    @Override
    protected void DataProcessingCenter(AppSession session, int protocol, int customer, byte[] content) {
        if (protocol == HslProtocol.ProtocolCheckSecends) {
            Date dt = new Date(Utilities.getLong(content, 0));
            ServerTime = new Date(Utilities.getLong(content, 8));
            DelayTime = (int) (new Date().getTime() - dt.getTime());
            this.session.setHeartTime(new Date());
            // MessageAlerts?.Invoke("心跳时间:" + DateTime.Now.ToString());
        } else if (protocol == HslProtocol.ProtocolClientQuit) {
            // 申请了退出
        } else if (protocol == HslProtocol.ProtocolUserBytes) {
            // 接收到字节数据
            if (AcceptByte != null) AcceptByte.Action(this, new NetHandle(customer), content);
        } else if (protocol == HslProtocol.ProtocolUserString) {
            // 接收到文本数据
            String str = Utilities.byte2String(content);
            if (AcceptString != null) AcceptString.Action(this, new NetHandle(customer), str);
        }
    }
 
 
    /**
     * 心跳线程的方法
     */
    private void ThreadHeartCheck() {
        try {
            Thread.sleep(2000);
        } catch (Exception ex) {
 
        }
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (Exception ex) {
 
            }
 
            if (!IsQuie) {
                byte[] send = new byte[16];
                byte[] buffer = Utilities.getBytes(new Date().getTime());
                System.arraycopy(buffer, 0, send, 0, buffer.length);
 
                try {
                    SendBytes(session, HslProtocol.CommandBytes(HslProtocol.ProtocolCheckSecends, 0, Token, send));
                    double timeSpan = (new Date().getTime() - session.getHeartTime().getTime()) / 1000;
                    if (timeSpan > 1 * 8)//8次没有收到失去联系
                    {
                        if (isConnecting == 0) {
                            if (LogNet != null)
                                LogNet.WriteDebug(toString(), "Heart Check Failed int " + timeSpan + " Seconds.");
                            new Thread(){
                                @Override
                                public void run() {
                                    ReconnectServer(null);
                                }
                            }.start();
                        }
                        if (!IsQuie) {
                            try {
                                Thread.sleep(1000);
                            } catch (Exception ex) {
 
                            }
                        }
                    }
 
                } catch (Exception ex) {
                    System.out.println(ex.getStackTrace());
                }
            } else {
                break;
            }
        }
 
 
    }
 
 
    /**
     * 返回对象的字符串表示形式
     *
     * @return 字符串
     */
    @Override
    public String toString() {
        return "NetComplexClient";
    }
}