0

我正在使用 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,那么我对其设置超时。

4

1 回答 1

-1

基本上你想要做的就是所谓的 com 端口重定向。首先你非阻塞读/写以确保应用程序永远不会卡在串行操作中。其次考虑使用 Thread.sleep 加上重试次数来使算法更强大。

尝试使用串行通信管理器库在 java 中进行串行端口通信。在 github 的源代码中查看 xmodem 的实现,因为它包含超时和基于 ACK 的读/写。

此外,它们是 com 端口重定向驱动程序,可以完全按照您的要求进行操作。如果您的项目允许考虑它们。另请参阅与您需要完全相同的端口服务器。如果您将使用简单的 TCP/IP 套接字,您还需要添加安全性。

于 2016-05-24T05:32:23.650 回答