我正在使用 Ingenico 终端进行交易处理。我使用套接字和串行端口与主服务器通信。
套接字和串口相互通信,即串口接收到的任何数据都会立即写入套接字的输出流,而套接字接收到的任何数据都会写入串口。
发生这种对话的顺序是:例如:当套接字向串口发送消息时,串口在一定的毫秒内响应一个ACK,然后串口向套接字发送另一个消息,反之亦然反之亦然。
我需要有一个超时机制来检查 in=receive an ACK 在一定的时间限制(几毫秒)内。为了做到这一点,我使用了 Timer 和 TimerTask。为了做到这一点,我从串行端口有条件地读取。我的问题是这是否可行?我在正确的轨道上吗?
到目前为止的代码:
public void serialEvent(SerialPortEvent event)
{
byte[] BytesFromSerialPort = null;
//timeout of 500ms to get either an ACK or NAK from the serial port or the socket on port 6000
int timeout = 10;
if(event.isRXCHAR() && event.getEventValue() > 0)
{
BytesFromSerialPort = new byte[event.getEventValue()];
try
{
if(IsAckExpected)
BytesFromSerialPort = serialPort.readBytes(event.getEventValue(), 1000*timeout);
else
BytesFromSerialPort = serialPort.readBytes(event.getEventValue());
//print statements
System.out.printf("SERIAL RX %04d: ", event.getEventValue());
for(byte b : BytesFromSerialPort)
System.out.printf("%c", (char)b);
System.out.println();
}
}
条件:如果预期的下一条消息是 ACK,那么我对其设置超时。