【发布时间】:2016-05-20 21:52:39
【问题描述】:
我正在使用 Ingenico 终端进行交易处理。我使用套接字和串口与主服务器通信。
socket和串口相互通信,即串口收到的任何数据都会立即写入socket的输出流,socket收到的任何数据都会写入串口。
发生了一系列对话: eg:当socket向串口发送消息时,串口在一定毫秒内响应ACK,然后串口向socket发送另一条消息,反之亦然。
我需要有一个超时机制来检查我是否在一定的时间限制(几毫秒)内收到了一个 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,则我对其设置超时。
【问题讨论】:
-
当您已经拥有一个已在使用的超时读取机制时,您不需要
Timer或TimerTask。不清楚你在问什么。 -
我只需要在套接字即将从串口接收到 ACK 时设置超时,反之亦然。当套接字和串行端口使用其他消息进行通信时,我不需要超时机制。使用 JSSC 的超时机制会对所有读取施加超时,这是我不希望的。
-
我明白了。我不需要计时器任务。但是下面的代码会起作用吗?我们可以根据条件为套接字读取设置不同的超时时间吗?
-
if(condition1) socket.setSoTimeout(timeout1); else if(condition2) socket.setSoTimeout(timeout2);
标签: java sockets serial-communication jssc