Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a structure:
C++
typedef struct{
    int flags;/*the type of message*/
    int length;/*the length of message*/
    void* message;/*the message*/
}Message;


The length of message is variable.For example:
C++
Message msg;
msg.flags=0;
char buf[]="abcdef";
msg.length=strlen(buf);
msg.message=buf;


How can i send the structure from client to the server with socket? Someone help me!or give me some advisements.
Posted

1 solution

The binary representation of your data in memeory and its serialized binary form that you write into stream (for example to a filestream, or pipe stream, or into a network stream backed by sockets) are often different.
You are curious about the serialization of your variable length string and about its deserialization on the other side of the connection. Its simple:
First you send the length of the string to your socket (for example as an int32) then you send the string data itself. On the other side of the connection you read out the length into a variable, and then you know how long the string is and how many bytes to read into your string.
 
Share this answer
 
v2
Comments
sum_and_sum 12-Aug-12 8:59am    
but i saw the function: ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);
the structure of msg like this:
<pre lang="c++">
struct msghdr {
void *msg_name; /* optional address */
socklen_t msg_namelen; /* size of address */
struct iovec *msg_iov; /* scatter/gather array */
size_t msg_iovlen; /* # elements in msg_iov */
void *msg_control; /* ancillary data, see below */
size_t msg_controllen; /* ancillary data buffer len */
int msg_flags; /* flags on received message */
};

struct iovec { /* Scatter/gather array items */
void *iov_base; /* Starting address */
size_t iov_len; /* Number of bytes to transfer */
};
</pre>

the ivo_base is variable arrary.
sum_and_sum 12-Aug-12 9:00am    
How to do like this function
pasztorpisti 12-Aug-12 9:06am    
You question is unclear. Where does this function come from and what do you want to know?
sum_and_sum 12-Aug-12 9:10am    
this function come from
sys/types.h
sys/socket.h

in linux c
pasztorpisti 12-Aug-12 9:12am    
OK, still I don't know what is your problem you can't solve. And why are you inspecting these structures in the linux headers?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900