Reputation: 2956
I'm trying to create a C# app that has two parts - Server and Client. The Client needs to communicate with the Server over a network (When testing, both parts would be on local computer communicating over "127.0.0.1"). I have tried to combine Sockets with serialization but had no luck.
I'm trying to serialize and send simple (test) object like this:
[Serializable]
class Test
{
public string msg="default";
}
This Class is defined both on the Server and in the Client code.
Sending code looks like this:
try
{
Test tst = new Test();
tst.msg = "TEST";
NetworkStream ns = new NetworkStream(m_socWorker);
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, tst);
m_socWorker.Send(ms.ToArray());
}
catch(System.Net.Sockets.SocketException se)
{
MessageBox.Show (se.Message );
}
Receiving code looks like this:
public void OnDataReceived(IAsyncResult asyn)
{
try
{
CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState ;
//end receive...
Test tst;
byte[] buffer = new byte[1024];
m_socWorker.Receive(buffer);
BinaryFormatter bin = new BinaryFormatter();
MemoryStream mem = new MemoryStream(buffer);
tst = (Test)bin.Deserialize(mem);
txtDataRx.Text = tst.msg;
theSockId.thisSocket.EndReceive(asyn);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
When I send data I receive an Exception -
"Exception of type 'System.OutOfMemoryException' was thrown."
pointing to the "Deserialization" line.
Is there anything glaringly obvious within my code that is causing a problem?
Upvotes: 0
Views: 2090
Reputation: 2874
I would suggest simplifying your code for testing:
Test your network sockets code using a simple string (eliminate the serialization from the mix to validate this first).
Test your serialization/deserialization code directly (without the extra complexity of the network sockets).
Once you have a better understanding of both pieces separately then you can start working on putting them together...
Luck
Upvotes: 1