简体   繁体   中英

How to include a header with the data that i send to a tcp server

I hope this is a good day to get a good answer. I have code that sends data to a TCP server. Am ok on sending the data but i do not know how to include the header. guidelines of how the header should be like are as follows

Communication between the Device and the XML interface uses a TCP message beginning with a header to indicate the length of the data segment of the message. This header must precede all messages sent to the XML interface, and will be sent at the beginning of all TCP responses from the XML interface.

If the message length is less than 2^16-1 or 65535 then a two-byte header will be used.

The first byte of the header contains the quotient of the length of the message (excluding this header) and 256. The second byte contains the remainder of this division. Both these values are represented in binary as unsigned integer values ranging from 0 to 255 (bytes 0x00 to 0xFF).

If the message length is greater than or equal to 216-1 or 65535 bytes then a six-byte header will be used.

In this case the bytes 0xFF 0xFF should be sent followed by a four-byte length indicator, ie six bytes in total.

Now what i have is as follows and and as you can see it doesn't address the header issue. Which is basically my question.

    private static void main2(String hostname, int port, String message)
    {

        String response = String.Empty;            
       TcpClient client = new TcpClient(hostname, port);  
        Console.WriteLine(message);
        NetworkStream stream = client.GetStream();
        StreamWriter writer = new StreamWriter(stream,Encoding.UTF8);

        writer.AutoFlush = false;            
        writer.WriteLine(message);          
        writer.Flush();           
        writer.Close();          

        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
        response = reader.ReadLine();

        stream.Close();
    }

Information does get to my TCP Server. (confirmed by using tcp viewer). But because i don't know how to include the header there is no way that the server can respond back to me as it is considering my request as not complete. Thanks in advance guys for your help.

Header they are talking about is not only a prefix of the message? They don't provide example? Try this (let's say message is less than 65535 bytes) :

var totalMessageLength = message.Length + 2;
var quotient = (int)totalMessageLength / 256;
var modulo = totalMessageLength % 256;
message = $"{quotient.ToString("X2")}{modulo.ToString("X2")}{message}";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM