Java对接串口、Modbus TCP/IP、Modbus UDP/IP的代码
时间: 2024-09-13 20:13:53 浏览: 47
在Java中处理串口通信通常需要使用`java.io`包下的`SerialPort`类,例如`javax.comm`库,它已经包含了对串口操作的基本支持。以下是一个简单的示例:
```java
import javax.comm.*;
public class SerialPortExample {
public static void main(String[] args) {
CommPortIdentifier portId = null;
CommPort commPort = null;
try {
// 获取所有串口设备列表
portId = CommPortIdentifier.getPortIdentifiers();
if (portId.size() > 0) {
CommPortIdentifier port = portId.nextElement();
// 检查是否是串口设备
if (port.getPortType() == CommPortType.COMPORT) {
commPort = port.open("MySerialPortApp", 2000);
// 设置波特率、数据位、停止位和校验位
((SerialPort)commPort).setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// 发送和接收数据
String dataToSend = "Hello from Java";
byte[] sendData = dataToSend.getBytes();
commPort.write(sendData, 0, sendData.length);
InputStream inStream = commPort.getInputStream();
byte[] receivedBytes = new byte[1024];
int bytesRead = inStream.read(receivedBytes);
String receivedData = new String(receivedBytes, 0, bytesRead);
System.out.println("Received: " + receivedData);
}
} else {
System.out.println("No serial ports found.");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (commPort != null) {
try {
commPort.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
}
```
对于Modbus TCP/IP和UDP/IP,你可以使用第三方库如`modbus-java`, `j Modbus`, 或者`MODBUS-TCP-CLIENT-JAVA`等。这些库提供了一套完整的API来连接和读写Modbus协议的数据。例如:
```java
import com.froglogic.jmodbus.ModbusClient;
import com.froglogic.jmodbus.data.UDPMulticastTransport;
// ... (其他依赖和配置)
try {
ModbusClient client = new ModbusClient(new UDPMulticastTransport(ipAddress, modbusPort));
client.connect();
// 发送请求(例如,读取输入寄存器)
short[] inputRegisters = client.readInputRegisters(startingRegister, quantityOfRegisters);
// 打印结果
for (short reg : inputRegisters) {
System.out.println("Input Register: " + reg);
}
client.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
阅读全文