在Java中實現Modbus TCP客戶端和服務器可以使用第三方庫如jamod或者j2mod來實現。以下是一個簡單的示例:
import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.net.TCPMasterConnection;
import net.wimpi.modbus.io.ModbusTCPTransaction;
import net.wimpi.modbus.msg.ReadInputDiscretesRequest;
import net.wimpi.modbus.msg.ReadInputDiscretesResponse;
import net.wimpi.modbus.util.ModbusUtil;
public class ModbusTCPClient {
public static void main(String[] args) {
try {
TCPMasterConnection connection = new TCPMasterConnection("127.0.0.1");
connection.setPort(502);
connection.connect();
ReadInputDiscretesRequest request = new ReadInputDiscretesRequest(0, 10);
ModbusTCPTransaction transaction = new ModbusTCPTransaction(connection);
transaction.setRequest(request);
transaction.execute();
ReadInputDiscretesResponse response = (ReadInputDiscretesResponse) transaction.getResponse();
if (response != null) {
for (int i = 0; i < response.getDiscretes().length; i++) {
System.out.println("Coil " + i + " = " + response.getDiscretes()[i]);
}
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import net.wimpi.modbus.procimg.SimpleDigitalIn;
import net.wimpi.modbus.procimg.SimpleDigitalOut;
import net.wimpi.modbus.procimg.SimpleProcessImage;
import net.wimpi.modbus.ModbusCoupler;
import net.wimpi.modbus.net.TCPListener;
public class ModbusTCPServer {
public static void main(String[] args) {
try {
ModbusCoupler.getReference().setProcessImage(new SimpleProcessImage());
ModbusCoupler.getReference().getProcessImage().addDigitalOut(new SimpleDigitalOut(true));
ModbusCoupler.getReference().getProcessImage().addDigitalIn(new SimpleDigitalIn(false));
TCPListener listener = new TCPListener(1);
listener.setPort(502);
listener.start();
System.out.println("Modbus TCP server running...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
這些示例代碼可以幫助你快速實現基本的Modbus TCP客戶端和服務器功能。你也可以根據需要進一步擴展和定制功能。