本文实现了socket进行发送modbus报文接收信息。
首先创建socket连接好对应的服务端。
Socket socket = new Socket("127.0.0.1", 502);//写对应的端口
socket.setSoTimeout(timeout);//超时时间
接着
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
byte[] sendInfo = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03,0x00, 0x01, 0x00, 0x01 };
byte[] sendInfo = new byte[] {0x01, 0x03,0x00, 0x01, 0x00, 0x01, 0xD5, 0xCA };
//tcp协议需要加上前面的报文头0x00, 0x00, 0x00, 0x00, 0x00, 0x06, rtu tcp需要在后面加上校验码 0xD5, 0xCA
os.write(sendInfo);
os.flush();
int count = 0;
while (count == 0) {
count = is.available();
}
byte[] b = new byte[count];
is.read(b);
b中数据就是得到的报文