A few years ago I wrote a small Stock trading TCP App while learning Socket
and at that time I didn't know about Json or binary serialization/deserialization and following along some articles/reply from this site or somewhere, I made a Struct
like this for transmission between clients and server:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct TradeItem
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]
public string Status;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string EndPoint;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string ItemName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
public string Mode;
public int Quantity;
public double Price;
public int PartyCode;
public int OrderNo;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string BrokerBought;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string BrokerSold;
public int PartySold;
public int PartyBought;
public int QtyTraded;
public double PriceTraded;
}
and for converting it to byte[]
and reverting to Struct
, I'd these helper methods:
public byte[] Pack(TradeItem ti)
{
int size = Marshal.SizeOf(ti);
byte[] array = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(ti, ptr, false);
Marshal.Copy(ptr, array, 0, size);
Marshal.FreeHGlobal(ptr);
return array;
}
public TradeItem UnPack(byte[] arr)
{
TradeItem ti = new TradeItem();
int size = Marshal.SizeOf(ti);
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(arr, 0, ptr, size);
ti = (TradeItem)Marshal.PtrToStructure(ptr, ti.GetType());
Marshal.FreeHGlobal(ptr);
return ti;
}
with all these I'd to send one item at a time! I still don't know how to deal with arbitrary size of List<TradeItem >
! If someone knows how to deal with List<TradeItem >
, It'd be nice to know that as well. Now I can send back and forth a single TradeItem
and/or List<TradeItem>
with Newtonsoft.Json
or BinaryFormatter
. Is there any benefit of using those kind of Marshaling/Cryptic Attributes over easy Serialization/Deserialization with Newtonsoft.Json
or BinaryFormatter
? Over my Local Network I always receive what I send with these:
//send
var data = new List<TradeItem>;
.
.
.
byte[] array = null;
using(var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, data);
array = stream.ToArray();
}
//receive
var formatter = new BinaryFormatter();
var list = formatter.Deserialize(new MemoryStream(e.Buffer)) as List<TradeItem>;
or
//send
var array = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
//receive
var json = Encoding.UTF8.GetString(e.Buffer);
var list = JsonConvert.DeserializeObject<List<TradeItem>>(json);
I just have to create a big enough byte[]
! Am I guaranteed to get what I send using these BinaryFormatter
and JsonConvert
provided that I've a big enough byte[]
?