1
Reply

Binary formatter issues with Sockets

dobby

dobby

Feb 10 2009 6:52 PM
3.6k
hi i have a class which i wish to send over a network using .net sockets. these are 2 separate proj in one solution, i have a Copy of the class file in each proj directory, with the name space changed in each file to match here is the code in the Sender. public Boolean SendCMD(StatusCMD toSend) { try { BinaryFormatter toBinary = new BinaryFormatter(); MemoryStream memStream = new MemoryStream(); toBinary.Serialize(memStream, toSend); Byte[] byToSend = new Byte[1024]; memStream.ToArray().CopyTo(byToSend, 0); memStream.Close(); BitConverter.GetBytes(Convert.ToInt16(memStream.ToArray().Length)).CopyTo(byToSend, 1022); netStream.Flush(); netStream.Write(byToSend, 0, byToSend.Length); return true; } catch { return false; } } this works fine, maybe your asking why i haven't just put the stream directly into the BF, but the size of the Class varies coz of strings in it. it manages to send the byte array with the last 2 byte indicate the point where the class stops. the server public StatusCMD[] ReciecveCMD() {//Recives a Status cammand try { List lstCMD = new List(); BinaryFormatter fromBinary = new BinaryFormatter(); MemoryStream memStream = new MemoryStream(); foreach (Socket currentSocket in Clients) { if (currentSocket.Available > 0) { Byte[] byRecCMD = new Byte[1024]; currentSocket.Receive(byRecCMD); Byte[] byTemp = new Byte[2]; byTemp[0] = byRecCMD[1022]; byTemp[1] = byRecCMD[1023]; Byte[] byObject = new Byte[BitConverter.ToInt16(byTemp, 0) + 1]; //byRecCMD.CopyTo(byObject,0); for (int i = 0; i < byObject.Length; i++) { byObject[i] = byRecCMD[i]; } memStream = new MemoryStream(); memStream.Flush(); memStream.Write(byObject, 0, byObject.Length); memStream.Position = 0; object k = fromBinary.Deserialize(memStream) ; //it always fails here lstCMD.Add(k as StatusCMD); lstCMD[lstCMD.Count - 1].CompID = currentSocket.RemoteEndPoint; } } memStream.Close(); return lstCMD.ToArray(); } catch(Exception e) { MessageBox.Show(e.ToString()); return null; } } it always fails at the BF'ing, and it just says a whole load of stuff about how the BF version my be different. when i look at the byte array that is going into the memstream it is the same as that which came out, of the senders. Please Help Me, i am newish to C# and sockets and binary formatting are new to me too. thank you for any help.

Answers (1)