严智鑫
2025-11-13 945bc394f40d8af1072a53da9a94f24207124e6d
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
package com.northglass.listener;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
 
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
 
import com.northglass.constants.ConnectState;
import com.northglass.entity.CountMachine;
import com.northglass.entity.CountMachineTask;
import com.northglass.log.GLoggerFactory;
import com.northglass.repository.CountMachineTaskDao;
import com.northglass.service.countmachine.CountMachineService;
import com.northglass.util.HexUtil;
 
public class CountMachineClientListener implements Runnable {
 
    private static final Logger LOGGER = GLoggerFactory.getLogger(CountMachineClientListener.class);
    
    private static final int INTERVAL = 5000;
    
    private static final int MESSAGE_LENGTH_START = 10;
    private static final int MESSAGE_LENGTH_END = 13;
    
    private static final int DATA_START = 74;
    
    /**
     * 信息头,字符串“<STA>”的16进制表示
     */
    private static final String HEAD = "3c5354413e";
    
    /**
     * 信息尾,字符串“<EOF>”的16进制表示
     */
    private static final String END = "3c454f463e";
    
    private StringBuffer MESSAGE_BUFFER = new StringBuffer();
    
    private CountMachine machineClient;
    private CountMachineService machineService;
    @Autowired
    private CountMachineTaskDao countMachineTaskDao;
    protected static final int BUFFER_SIZE = 2048;
    protected byte[] msg = new byte[BUFFER_SIZE];
    protected int bufSize = 0;
    
    // 该方法Jetty中用不到,但是Tomcat中可能会有问题
    private ApplicationContext initializeSpringContext() {
        GenericXmlApplicationContext context = new GenericXmlApplicationContext();
        context.getEnvironment().setActiveProfiles("production");
        context.load("applicationContext.xml");
        context.refresh();
        
        return context;
    }
    
    public CountMachineClientListener(CountMachine machineClient, CountMachineService machineService) {
        initializeSpringContext();
        this.machineClient = machineClient;
        this.machineService = machineService;
    }
    
    private void connect() {
        Socket socket = null;
        
        while (socket == null) {
            try {
                socket = new Socket(machineClient.getIpAddress(), machineClient.getPort());
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    Thread.sleep(3000);
                } 
                catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
        
        LOGGER.debug("【" + machineClient.getNumber() + "】启动连接服务器,端口:" + machineClient.getPort());
        
        machineService.setConnectState(machineClient,ConnectState.CONNECTED);//ConnectState.CONNECTED
        machineClient.getServerConnection().setSocket(socket);
        
        try {
            DataOutputStream writer = new DataOutputStream(socket.getOutputStream());
            DataInputStream reader = new DataInputStream(socket.getInputStream());
            
            while (true) {
                String returnMessage = machineService.getmessage(machineClient);
                writer.writeUTF(returnMessage + "\n");
                writer.flush();
                String message = reader.readUTF();
                System.out.println("message: " + message);
//                List<CountMachineTask> inWorkTasks = machineService.findInWorkTask(machineClient);
//                if (message.equals("0001") && tasks.size()>0) {
//                    CountMachineTask task = tasks.get(0);
//                    task.setState("已完成");
//                    machineService.saveCountMachineTask(task);
//                }
                Thread.sleep(1000);
            }
        }
        catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    private void listen() throws IOException {
        Socket socket = machineClient.getServerConnection().getSocket();
        socket.setSoTimeout(3000);
        
        while(true) {
             BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             String message = reader.readLine();
             System.out.println("message: " + message);
        
            String returnMessage = machineService.processMessage(message,machineClient);
            System.out.println("returnMessage: " + returnMessage);
            
            if (returnMessage != null && !"".equals(returnMessage)) {
                OutputStream os = socket.getOutputStream();
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
                bw.write(sendMessage() + "\n");
                bw.flush();
//                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//                out.write(HexUtil.stringToInt(returnMessage));
//                out.flush();
            } else {
//                DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
                OutputStream os = socket.getOutputStream();
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                
                bw.write(sendMessage() + "\n");
                bw.flush();
            }
        }
    }
 
    public boolean existMessage() {
        // 若缓冲区长度小于消息最小长度,则缓冲区中的消息无效。
        if (MESSAGE_BUFFER.length() < 84) {
            return false;
        }
        
        String head = MESSAGE_BUFFER.substring(0, 10);
        LOGGER.trace("head: " + head);
        
        // 若缓冲区不以HEAD为起始,则删掉字符;
        // 一个字符一个字符删是避免一次删多导致消息损坏。
        if (!head.equalsIgnoreCase(HEAD)) {
            MESSAGE_BUFFER.delete(0, 2);
            return false;
        }
        
        // 获取消息长度
        String messageLengthHex = MESSAGE_BUFFER.substring(MESSAGE_LENGTH_START, MESSAGE_LENGTH_END + 1);
        int messageLength = HexUtil.hexToInt(messageLengthHex);
        LOGGER.trace("messageLength: " + messageLength);
        
        if (MESSAGE_BUFFER.length() < DATA_START + messageLength*2) {
            return false;
        }
        
        String dataAndEnd = MESSAGE_BUFFER.substring(DATA_START, DATA_START + messageLength*2);
        String end = dataAndEnd.substring(dataAndEnd.length() - 10, dataAndEnd.length());
        LOGGER.trace("end: " + end);
        
        if (head.equals(HEAD) && end.equals(END)) {
            return true;
        }
                
        return false;
    }
    
    public String getNextMessage() {
        // 获取消息长度
        String messageLengthHex = MESSAGE_BUFFER.substring(MESSAGE_LENGTH_START, MESSAGE_LENGTH_END + 1);
        int messageLength = HexUtil.hexToInt(messageLengthHex);
        LOGGER.trace("messageLength: " + messageLength);
        
        String message = MESSAGE_BUFFER.substring(0, DATA_START + messageLength*2);
        MESSAGE_BUFFER.delete(0, DATA_START + messageLength*2);
        
        return message;
    }
    
    @Override
    public void run() {
        //while (true) {
            try {
                connect();
                //listen();
            }
            catch (Exception e) {
                e.printStackTrace();
                
                LOGGER.error("下片【" + machineClient.getNumber() + "】无法连接服务器:【" 
                        + machineClient.getIpAddress() + ":" + machineClient.getPort() + "】!");
                
                try {
                    Thread.sleep(INTERVAL);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            } 
        //}
    }
    
    private String sendMessage() {
        String date = "0000";
        return date;
    }
 
}