Search code examples
c#tcpclientmodbus-tcp

TcpClient connecting but not getting data


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


Solution

  • 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 };