I need to build up a message which is to be sent down a TCP socket, but I am completely confused as to how to do so.
I've created and connected the socket in a class derived from CAsyncSocket (I have to use MFC).
I then need to build up the message I need to send. If the message was 2 bytes long, I will create a byte array with 2 elements (ie 1 byte per element). Then I would set each of these 1 byte elements to a hex value. Then pass it to the socket buffer to be sent to the TCP server.
MFC is a business requirement for the code I am working on.
The socket side of things is OK. It seems really easy to do it with CAsyncSocket. My problem is coming with building up the message in hex values, then converting it to an ascii stream of hex characters (as thats how I presume I need to do it).
I am using char* variables to represent the elements of the frame/message which are 1 byte in length, and unsigned short int's to represent elements which are 2 bytes long.
From here, I guess the char's can be transmitted as they are (is this correct?), and the unsigned short int's need to be converted to a string. All elements are ordered then to be ordered correctly in elements of an array (unsigned char?) and transmitted over the socket connection.
In saying that, I'm not sure if I am even correct in that method. Either way, I would really appreciate some help implementing this :)
A char is 1 byte by definition. From then on integral types vary in size. If you're using VS2010, you should have stdint.h and you can use int16_t for two bytes. Otherwise, you'll have to go with a platform specific definition and unsigned short is as good a choice as anything else on Win32.
Don't try to send 1 byte or 2 byte packets; instead try to larger records.
You can encode the unsigned short using htons, i.e. send it as binary in network order. That way you can still send two bytes rather than converting to/from string.