Sending a struct over TCP

SirErugor ontherenth at gmail.com
Tue Mar 6 14:26:39 PST 2007


Hi there,

I've set up a server and a client application and I want to be able to send a struct with fx. an integer and a char[]. So first I convert it to a ubyte[] like this:

..
void write(T)(T input)
{
    buf ~= *(cast(ubyte[T.sizeof]*)&input)[0 .. T.sizeof];
}

Then I send the ubyte[] over through TCP via a SocketStream. On the client-side I read and convert the ubyte[] back to the struct:

uint len = ss.read(buffer);
auto mem = new mem_stream(buffer[0 .. len]);
data d = mem.read!(data);
writefln("[id:%d] len=%d, data=%s (%d)", d.id, len, d.content, d.content.sizeof);

Which outputs:    [id:100] len=12, data= (8)

The read function:
..
int pos = 0;
..
T read(T)()
{
     T output = *(cast(T*)(buf[pos .. pos + T.sizeof].ptr));
     pos += T.sizeof;
     return output;
}

The Integer got sent perfectly (and i does the same with additional ulongs etc.) but the char[] did not, though, it is still the same size.

So why can't I send the char[]? is it because it is a array of pointers to the address-space of the server?

Thank you in advance :)

(Btw. My files are also attatched)
-------------- next part --------------
A non-text attachment was scrubbed...
Name: client.d
Type: text/x-dsrc
Size: 1164 bytes
Desc: not available
Url : http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20070306/6a877390/attachment.d 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: data_struct.d
Type: text/x-dsrc
Size: 62 bytes
Desc: not available
Url : http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20070306/6a877390/attachment-0001.d 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: memstream.d
Type: text/x-dsrc
Size: 408 bytes
Desc: not available
Url : http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20070306/6a877390/attachment-0002.d 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: server.d
Type: text/x-dsrc
Size: 2969 bytes
Desc: not available
Url : http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20070306/6a877390/attachment-0003.d 


More information about the Digitalmars-d-learn mailing list