5

I'm pretty new to serialization so please bear with me.

I want two instances of my application to communicate with each other over the internet. I have successfully rigged up a TCP client/server relationship and used a binary formatter to get the two sides to swap a single pair of messages. Here's the client side...

using (TcpClient clientSocket = new TcpClient(ipAddress, currentPort))
{
    using (NetworkStream stream = clientSocket.GetStream())
    {
        // send
        bformatter.Serialize(stream, new Message());

        // recv
        return (Message)bformatter.Deserialize(stream);
    }
}

It's cool, but not very useful for an application that needs to send messages in response to user events. So I need to be able to send and receive asynchronously.

I basically want an interface that behaves like this:

class BidirectionalObjectStream
{
    public BidirectionalObjectStream(TcpClient client)
    {
        //...
    }

    // objects go in here
    public void SendObject(object o)
    {
        //...
    }

    // objects come out here
    public event Action<object> ObjectReceived;
}

Is there a class like this that's part of .NET? If not, how should I implement the receive event? Maybe a dedicated thread calling bformatter.Deserialize() repeatedly...?

Any help appreciated.

Neal Ehardt
  • 10,334
  • 9
  • 41
  • 51
  • "used a binary formatter" Don't do this unless you 100% trust your communication partner. `BinaryFormatter` allows low level access to fields and thus most likely allows arbitrary code execute in the context of your program for the sender of a message. Consider using json or protobuf for your messages. – CodesInChaos Jul 16 '11 at 20:26

1 Answers1

1

The question is a little broad.

I can think of two options:

  • Use asynchronous socket. Using an Asynchronous Client Socket
  • Create separate threads for receiving and sending. There many ways to achieve it, raw Thread, ThreadPool, delegate.Invoke, new TPL features like Task and Parallel.
Alex Aza
  • 76,499
  • 26
  • 155
  • 134