package com.northglass.listener;
|
|
import java.io.DataInputStream;
|
import java.io.DataOutputStream;
|
import java.io.IOException;
|
import java.net.ServerSocket;
|
import java.net.Socket;
|
import java.text.SimpleDateFormat;
|
import java.util.ArrayList;
|
import java.util.Date;
|
import java.util.List;
|
|
import org.slf4j.Logger;
|
import org.slf4j.MDC;
|
import org.springframework.context.ApplicationContext;
|
import org.springframework.context.support.GenericXmlApplicationContext;
|
|
import com.northglass.constants.ConnectState;
|
import com.northglass.constants.MessageType;
|
import com.northglass.entity.AbstractMachine;
|
import com.northglass.log.GLoggerFactory;
|
import com.northglass.service.common.AbstractMachineService;
|
import com.northglass.util.HexUtil;
|
|
public class ServerListener implements Runnable {
|
|
private static final Logger LOGGER = GLoggerFactory.getLogger(ServerListener.class);
|
|
private StringBuffer MESSAGE_BUFFER = new StringBuffer();
|
|
private AbstractMachine machine;
|
private AbstractMachineService machineService;
|
|
private static List<AbstractMachine> machineList = new ArrayList<AbstractMachine>();
|
|
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";
|
|
// 该方法Jetty中用不到,但是Tomcat中可能会有问题
|
private ApplicationContext initializeSpringContext() {
|
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
|
context.getEnvironment().setActiveProfiles("production");
|
context.load("applicationContext.xml");
|
context.refresh();
|
|
return context;
|
}
|
|
public ServerListener(AbstractMachine machine, AbstractMachineService machineService) {
|
initializeSpringContext();
|
this.machine = machine;
|
this.machineService = machineService;
|
MDC.put("logFileName", this.machine.getClass().getSimpleName() + "_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()));
|
}
|
|
public static List<AbstractMachine> getMachineList() {
|
return machineList;
|
}
|
|
public static AbstractMachine getMachine(String machineNumber) {
|
for (AbstractMachine machine : machineList) {
|
if (machine.getNumber().equals(machineNumber)) {
|
return machine;
|
}
|
}
|
|
return null;
|
}
|
|
public static void removeMachine(String machineNumber) {
|
for (AbstractMachine machine : machineList) {
|
if (machine.getNumber().equals(machineNumber)) {
|
machineList.remove(machine);
|
}
|
}
|
}
|
|
private void connect(ServerSocket serverSocket) throws IOException {
|
if (serverSocket.isClosed()) {
|
return;
|
}
|
|
Socket socket = serverSocket.accept();
|
LOGGER.debug("客户端已连接,客户端IP:" + socket.getInetAddress());
|
|
machineService.setConnectState(machine, ConnectState.CONNECTED);
|
machine.getServerConnection().setSocket(socket);
|
machineList.add(machine);
|
}
|
|
private void listen() throws IOException {
|
Socket socket = machine.getServerConnection().getSocket();
|
socket.setSoTimeout(15000);
|
|
while(true) {
|
DataInputStream in = new DataInputStream(socket.getInputStream());
|
byte b = in.readByte();
|
MESSAGE_BUFFER.append(HexUtil.byteToHexString(b));
|
|
if (!existMessage()) {
|
continue;
|
}
|
|
String message = getNextMessage();
|
machineService.saveMessage(MessageType.CLIENT, message, socket.getInetAddress().getHostAddress(), socket.getLocalPort());
|
String returnMessage = machineService.processMessage(message, machine);
|
|
if (returnMessage != null && !"".equals(returnMessage)) {
|
machineService.saveMessage(MessageType.SERVER, message, socket.getInetAddress().getHostAddress(), socket.getLocalPort());
|
|
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
|
out.write(HexUtil.stringToInt(returnMessage));
|
out.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() {
|
ServerSocket serverSocket = null;
|
|
try {
|
serverSocket = new ServerSocket(machine.getPort());
|
LOGGER.debug("【" + machine.getNumber() + "】启动监听,等待客户端连接,端口:" + machine.getPort());
|
machine.getServerConnection().setServerSocket(serverSocket);
|
|
connect(serverSocket);
|
|
// 一直循环,若连接断开,则在Exception处理环节重新连接,并继续监听消息
|
while (!Thread.currentThread().isInterrupted()) {
|
try {
|
listen();
|
}
|
catch (IOException se) {
|
LOGGER.debug("【" + machine.getNumber() + "】连接已断开!");
|
se.printStackTrace();
|
|
LOGGER.debug("【" + machine.getNumber() + "】等待重新连接……");
|
machineService.setConnectState(machine, ConnectState.CONNECTING);
|
connect(serverSocket);
|
}
|
}
|
}
|
catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|