Re: [gnet] Using pack to pack an array
- From: Anna <christiana hipointcoffee com>
- To: gnet lists gnetlibrary org
- Subject: Re: [gnet] Using pack to pack an array
- Date: Thu, 27 Jul 2006 03:42:17 -0700
On Wed, Jul 26, 2006 at 10:26:19PM +0200, Jon Kristensen wrote:
> Hello people!
>
> First of all, thanks for a great library! :o)
>
> My problem is that I want to send a standard C++ array of structs using
> pack, while I can't figure out a way to do it. This is what I want to
> pack (and unpack):
>
> #define MAX_NUMBER_OF_CLIENTS 10
>
> struct pos
> {
> int x, y;
> };
>
> static pos positions[MAX_NUMBER_OF_CLIENTS];
try...
typedef
struct pos
{
int x, y;
} pos_t ;
typef
struct mypacket
{
pos_t positions[MAX_NUMBER_OF_CLIENTS];
} mypacket_t;
int main()
{
printf("%d\n", sizeof(mypacket_t) );
/* that should print a number that's (2*MAX_NUMBER_OF_CLIENTS),
* which means it's already serialized and ready to send over the
* network. just send it in a tcp stream. */
}
====================================================================
better yet.
typedef
struct pos
{
int x, y;
} pos_t ;
typef
struct mypackethead
{
uint32_t count;
} mypackethead_t;
int make_packet_and_send()
{
int poscount = 30;
mypackethead_t * packet = NULL;
pos_t * poses = NULL;
int packetsize = 0;
packetsize = sizeof(mypackethead_t) + (sizeof(pos_t) * poscount);
/* allocate a continuous block of memory */
packet = malloc( packetsize );
if( packet )
{
memset( packet, 0, packetsize );
packet->count = poscount;
poses = (pos_t*)(packet+1);
for(i = 0; i < poscount; i++ )
{
poses[i].x = i*3 /* whatever */ ;
poses[i].y = i*25 /* whatever */ ;
}
send(packet, packetsize);
/* make sure all data is "sent" (in kernel-space_ before freeing */
free( packet );
}
...;
}
====================================================================
ie, make your protocol flexible by adding information to the head of
each packet.
- Anna
[
Date Prev][Date Next] [
Thread Prev][Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]