Send and receive in socket
BCS
BCS at pathlink.com
Wed Aug 15 13:03:06 PDT 2007
Downs wrote:
> Charma wrote:
>
>>Hello,
>>I try to use the std.socket to send data from a client to a "server". Up
>>to now i managed to get a connection and to send strings and chars of
>>text but i am not able to send and receive floats or other types of
>>numbers...
>>Maybe anyone knows how to do that?
>>the socket-command only accepts void[] and i have no idea how to make an
>>array from the 4 bytes that a float has...
>>
>>Thanks for any help,
>>sorry for my engrish...
>>
>>Charma
>
> well there's always the cheap way to do it
> void socksend(T)(Socket s, T value) { s.send((cast(void
> *)&T)[0..T.sizeof]); }
>
> Note that this will break utterly for reference types and arrays, but
> you get the basic idea. It would probably be possible to make an
> extended version via static if that handles arrays correctly (deep
> copying), but I'm too lazy. :p
> --downs
I've got a template that does deep copies of ragged arrays to a buffer
that can then be reconstructed on the other end of a pipe.
Almost no docs, no type checking, haven't used it with dmd >~0.160, and
I forget how to make it work... so have fun ;)
struct Array
{
uint start;
uint length;
}
T[] MakeArray(T)(Array head, byte[] buf)
{
if(head.start + head.length*T.sizeof > buf.length)
throw new ArrayConstructionError("Array mapping exceeded buffer");
return (cast(T*)&buf[head.start])[0..head.length];
}
template TArray(T)
{
// data: what to send
// meta: generated meta data
// buf: array of buffers containing data
// i: size of all of buf data
Array Load(T[] data,inout Array[] meta,inout byte[][] buf,inout uint i)
{
Array ret;
static if(is(typeof(data[0][0])))
{
ret.start = meta.length;
ret.length = data.length;
meta.length = meta.length + data.length;
foreach(int j, a;data)
meta[ret.start+j]=TArray!(typeof(data[0][0])).Load(a,meta, buf, i);
}
else
{
ret.start = i;
ret.length = data.length;
buf ~= (cast(byte*)data.ptr)[0..data.length*T.sizeof];
i += buf[$-1].length;
}
return ret;
}
// buf: cat of buf's from Load
T[] UnLoad(Array arr, Array[] meta, byte[] buf)
{
static if(is(typeof(T[0])))
{
T[] ret;
ret.length = arr.length;
foreach(int j, a; meta[arr.start..arr.start+arr.length])
ret[j] = TArray!(typeof(T[0])).UnLoad(a,meta, buf);
return ret;
}
else
return MakeArray!(T)(arr, buf);
}
}
More information about the Digitalmars-d-learn
mailing list