![](https://csdnimg.cn/release/download_crawler_static/88593402/bg5.jpg)
String ipAddress = "127.0.0.1"; // 替换为你的 Modbus 设备的 IP 地址
int port = 502; // 替换为你的 Modbus 设备的端口号
try {
ModbusCoupler.setDefaultModbusCoupler(new ModbusCoupler());
TCPMasterConnection connection = new TCPMasterConnection(ipAddress);
connection.setPort(port);
connection.connect();
ModbusTCPTransaction transaction = new ModbusTCPTransaction(connection);
// 批量读取保持寄存器
ReadMultipleRegistersRequest readRequest = new
ReadMultipleRegistersRequest(0, 5);
transaction.setRequest(readRequest);
transaction.execute();
ReadMultipleRegistersResponse readResponse =
(ReadMultipleRegistersResponse) transaction.getResponse();
if (readResponse != null) {
int[] readValues = readResponse.getRegisters().toIntArray();
System.out.println("Read values from Modbus: " +
arrayToString(readValues));
} else {
System.out.println("Modbus read request failed");
}
// 批量写入保持寄存器
WriteMultipleRegistersRequest writeRequest = new
WriteMultipleRegistersRequest(0, new Register[]{new SimpleRegister(10), new
SimpleRegister(20), new SimpleRegister(30)});
transaction.setRequest(writeRequest);
transaction.execute();
WriteMultipleRegistersResponse writeResponse =
(WriteMultipleRegistersResponse) transaction.getResponse();
if (writeResponse != null) {
System.out.println("Modbus write request successful");
} else {
System.out.println("Modbus write request failed");
}
connection.close();