Java 监听modbustcp
时间: 2023-12-22 11:04:51 浏览: 112
以下是Java监听ModbusTCP的示例代码:
```java
import java.net.*;
import java.io.*;
public class ModbusTCPServer {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(502);
System.out.println("Modbus TCP server is listening...");
while (true) {
Socket socket = server.accept();
System.out.println("Client connected: " + socket.getRemoteSocketAddress());
// 处理客户端请求
Thread thread = new Thread(new ModbusTCPHandler(socket));
thread.start();
}
}
}
class ModbusTCPHandler implements Runnable {
private Socket socket;
public ModbusTCPHandler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
// 处理Modbus TCP请求
// ...
in.close();
out.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
该示例代码创建了一个ServerSocket对象,监听Modbus TCP的默认端口502。当有客户端连接时,会创建一个新的线程来处理客户端请求。在ModbusTCPHandler类的run方法中,可以处理Modbus TCP请求并返回响应。
阅读全文