0

i've got to handle a serial communication between a client and a server in java and on windows platform. i am using the JSSC lib (tried 0.9 and 2.6), but I've got the problem that I can't receive data. I am using a virtual bridging software for emulating a nullmodem device connection (http://www.hhdsoftware.com/free-virtual-serial-ports).

the ports itself are opened with default parameters (9600, 8, 1, 0).

if i am using the hyperterminal software of microsoft i can see that the data is sent and received in bidirectional ways. on the other hand if i am trying to communicate with two eclipse projects, whereas one send a signal (writeBytes()) and the other receives the signal (readBytes()), the signal won't make it to the readBytes method. i only get null as return value from the read method. for the signal itself i've tried from byte[] to string with and w/o \r\n.

OS: WIN7_x64

what am I doing wrong?

feel free to ask if some information are missing or sth. is unclear.

kind regards and thanks in advance.

4

2 回答 2

2

当您调用readBytes()不带参数的方法时,jSSC 尝试从串口读取所有可用数据,如果串口输入缓冲区为空,则方法立即返回null值。

为了正确处理传入数据,您应该使用SerialPortEventListener接口,代码示例:

class SerialPortReader implements SerialPortEventListener {

    public void serialEvent(SerialPortEvent event) {
        if (event.isRXCHAR() && event.getEventValue() > 0) {//If data is available
            int bytesCount = event.getEventValue();
            System.out.print(serialPort.readString(bytesCount));
        }
    }
}

您应该将 SerialPortReader 类型的对象分配给您的串行端口对象,如下所示:

serialPort.addEventListener(new SerialPortReader());

另一种方法是使用内部带有 read 方法的循环,如下所示:

try {
    while (true) {
        if (serialPort.getInputBufferBytesCount() > 0) {
            System.out.print(serialPort.readString());
        }
        Thread.sleep(100);
    }
} catch (Exception ex) {
    System.out.prinln(ex);
}

但我强烈建议您使用SerialPortEventListener,因为它在独立线程中运行并使用特定于串行端口的 API。

于 2013-07-30T19:40:01.743 回答
0

通过卸载虚拟com端口的仿真软件并使用管理员权限和 bcdedit.exe -set TESTSIGNING ON.

于 2013-07-31T15:22:33.140 回答