Warm tip: This article is reproduced from stackoverflow.com, please click
c# modbus-tcp tcpclient

TcpClient connecting but not getting data

发布于 2020-05-25 18:25:56

I have TcpClient connection to a tcp device using modbus protocol. I get a timeout exception on the Read or if I remove the timeout it goes until I stop the program. But I can use a Tcp Terminal program to get the data. What am I doing wrong?

    static void Main(string[] args)
    {
        var client = new TcpClient("192.168.1.10", 502);
        var message = new byte[] { 0x00, 0x02, 0x00, 0x00, 0x06, 0x00, 0x04, 0x00, 0x00, 0x00, 0x02 };
        var stream = client.GetStream();
        stream.ReadTimeout = 3000;
        stream.Write(message, 0, message.Length);            
        var buffer = new byte[13];
        stream.Read(buffer, 0, 13);
        Console.WriteLine(buffer.Select(x => x.ToString("X")));
    }

enter image description here

Questioner
Clayton Harbich
Viewed
12
ATTA 2020-03-10 13:52

The assigned value to 'var message' is not the same as you are sending through TCP Terminal.

try to send 12 bytes:

var message = new byte[] { 0x00, 0x02, 0x00, 0x00, 0x00, 0x06, 0x00, 0x04, 0x00, 0x00, 0x00, 0x02 };