How to get an asynchronous stream of TCP objects in C #?

I am new to serialization, so please bear with me.

I want two instances of my application to communicate with each other over the Internet. I successfully modeled the TCP / client and server communications and used a binary formatter so that both sides exchange 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);
    }
}

This is cool, but not very useful for an application that should send messages in response to user events. Therefore, I need to be able to send and receive asynchronously.

I basically need 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 such a class that is part of .NET? If not, how do I implement a receive event? Maybe a dedicated thread calling bformatter.Deserialize()several times ...?

.

+5
1

.

:

  • .
  • . , raw Thread, ThreadPool, delegate.Invoke, TPL, Task Parallel.
+1

All Articles