Completely Confused: Sending Hex Values

Hi,

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.

Is this correct?
Why are you using MFC classes? There are plenty (30 years worth) of examples using standard sockets, WinSock in your case.
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 :)
I can't help with the CAsynSocket thing.

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.
Thanks for your reply :) Not sure I write understand the last 2 paragraphs.

I'm actually using VVC++ 6.0, I have no say in the matter unfortunately.

I will have a look at the htons function and see if I can understand what you mean!

I have been thinking about using a union, declaring a struct within, and an unsigned char array. Example below.

1
2
3
4
5
6
7
8
9
10
union
{
          struct 
          {
                    unsigned short int seg1, seg2;
                    char* seg3;
          }
     
          unsigned char msg[5]
}


Then I would send the char array 'message'. Would this work?
You to think about how you send the data and how you might receive it too.
Topic archived. No new replies allowed.