简体   繁体   中英

Sending objects over network

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?

I would suggest simplifying your code for testing:

  1. Test your network sockets code using a simple string (eliminate the serialization from the mix to validate this first).

  2. Test your serialization/deserialization code directly (without the extra complexity of the network sockets).

  3. Once you have a better understanding of both pieces separately then you can start working on putting them together...

Luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM