Example code for implementing Modbus TCP Server based on Java, using Jamod library

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

Example code for implementing Modbus TCP Server based on Java, using Jamod library缩略图

import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.ModbusCoupler;
import net.wimpi.modbus.io.ModbusTCPListener;
import net.wimpi.modbus.procimg.*;
import net.wimpi.modbus.util.*;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class ModbusTCPServerExample {

  public static void main(String[] args) {

    try {
      // 创建一个实现了ModbusSlave接口的SimpleProcessImage
      SimpleProcessImage spi = new SimpleProcessImage();
      spi.addDigitalOut(new SimpleDigitalOut(true));
      spi.addDigitalIn(new SimpleDigitalIn(false));
      spi.addInputRegister(new SimpleInputRegister(45));
      spi.addRegister(new SimpleRegister(251));
      ModbusCoupler.getReference().setProcessImage(spi);
      ModbusCoupler.getReference().setMaster(false);
      ModbusCoupler.getReference().setUnitID(1);

      // 获取本地IP地址
      InetAddress addr = InetAddress.getLocalHost();
      String ipAddress = addr.getHostAddress();

      // 创建ModbusTCPListener对象,监听指定端口
      ModbusTCPListener listener = new ModbusTCPListener(1);
      listener.setAddress(addr);
      listener.open();

      // 打印服务器信息
      System.out.println("Modbus TCP server running at " + ipAddress + ":" + Modbus.DEFAULT_PORT);

    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

This example code creates a simple Modbus TCP server that uses a SimpleProcessImage that implements the Modbus Slave interface to store data. SimpleProcessImage includes a digital output, a digital input, an input register, and a hold register. In the main function, first create a SimpleProcessImage, and then set it as the process image for Modbus Couple. Then, set the master/slave mode of the Modbus Coupler to slave mode and set the unit ID to 1. Next, obtain the local IP address and use the Modbus TCP Listener object to listen on the default port (502). Finally, print the server information.

Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

Leave a Reply

Your email address will not be published. Required fields are marked *.