我正在使用jamod库在 Java 中开发 Modbus/TCP 主应用程序。在从我的从设备连续读取期间,连接被突然关闭。
我的代码:
import net.wimpi.modbus.io.ModbusTCPTransaction;
import net.wimpi.modbus.msg.ReadMultipleRegistersRequest;
import net.wimpi.modbus.msg.ReadMultipleRegistersResponse;
import net.wimpi.modbus.net.TCPMasterConnection;
public static void main(String[] args) throws Exception {
TCPMasterConnection connection = new TCPMasterConnection(InetAddress.getByName("192.168.0.111"));
connection.setPort(502);
connection.connect();
if (!connection.isConnected())
return;
System.out.println(readIntFromIntAddr(connection, 256));
System.out.println(readIntFromIntAddr(connection, 256));
System.out.println(readIntFromIntAddr(connection, 256));
System.out.println(readIntFromIntAddr(connection, 256));
System.out.println(readIntFromIntAddr(connection, 256));
System.out.println(readIntFromIntAddr(connection, 256));
}
private static synchronized int readIntFromIntAddr(TCPMasterConnection connection, int address) throws Exception {
ReadMultipleRegistersRequest Rreq = new ReadMultipleRegistersRequest(address, 1); // reading one register
Rreq.setUnitID(1); // slaveAddress
ModbusTCPTransaction trans = null;
trans = new ModbusTCPTransaction(connection);
trans.setRetries(3);
trans.setReconnecting(true);
trans.setRequest(Rreq);
trans.execute();
ReadMultipleRegistersResponse Rres = (ReadMultipleRegistersResponse) trans.getResponse();
return Rres.getRegisterValue(0);
}
在第 6 次阅读期间抛出的错误
net.wimpi.modbus.ModbusIOException: Premature end of stream (Header truncated).
at net.wimpi.modbus.io.ModbusTCPTransport.readResponse(ModbusTCPTransport.java:190)
at net.wimpi.modbus.io.ModbusTCPTransaction.execute(ModbusTCPTransaction.java:192)
at cz.jlochman.marklar.drivers.connection.modbustcp.ModBusTcpConnection.readIntFromIntAddr(ModBusTcpConnection.java:280)
at cz.jlochman.marklar.drivers.connection.modbustcp.ModBusTcpConnection.main(ModBusTcpConnection.java:267)
出现此错误后,我无法恢复连接。我必须终止我的应用程序线程并再次启动应用程序。我找到了一些解决方法:Thread.sleep(500)
在第 5 次阅读后添加会消除此异常。Thread.sleep(200)
每次阅读后也有效。不幸的是,这些变通方法不足以满足我从从设备连续读取的需求。
有谁知道,会发生什么?