Maven引入j2mod包,我使用3.1.1版本
<dependency>
<groupId>com.ghgande</groupId>
<artifactId>j2mod</artifactId>
<version>3.1.1</version>
</dependency>
直接上例子代码:
package com.fuyan.test.modbus.slave;
import com.ghgande.j2mod.modbus.ModbusException;
import com.ghgande.j2mod.modbus.procimg.*;
import com.ghgande.j2mod.modbus.slave.ModbusSlave;
import com.ghgande.j2mod.modbus.slave.ModbusSlaveFactory;
/**
* @Description: Modbus TCP 从站(服务端)
* @Author fuyan.wang
* @Date 2024/5/10
*/
public class ModbusTCPSlave {
public static void main(String[] args) {
// 简单添加几个测试数据
SimpleProcessImage spi = new SimpleProcessImage();
// 线圈状态
spi.addDigitalOut(new SimpleDigitalOut(true));
spi.addDigitalOut(new SimpleDigitalOut(false));
// 输入状态
spi.addDigitalIn(new SimpleDigitalIn(true));
spi.addDigitalIn(new SimpleDigitalIn(true));
spi.addDigitalIn(new SimpleDigitalIn(false));
spi.addDigitalIn(new SimpleDigitalIn(true));
// 保持寄存器
spi.addRegister(new SimpleRegister(200));
spi.addRegister(new SimpleRegister(99));
// 输入寄存器
spi.addInputRegister(new SimpleInputRegister(44));
spi.addInputRegister(new SimpleInputRegister(55));
// 端口
int port = 502;
// 连接池大小(简单理解就是允许多少个主站同时连接)
int poolSize = 2;
// 从站Id
int unitId = 1;
try {
ModbusSlave slave = ModbusSlaveFactory.createTCPSlave(port,poolSize);
slave.addProcessImage(unitId,spi);
// 多个从站就多个addProcessImage就可以了
// 启动从站服务
slave.open();
// 关闭(自定处理)
//ModbusSlaveFactory.close();
} catch (ModbusException e) {
// 处理异常...
//...
throw new RuntimeException(e);
}
}
}