Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get an asynchronous TCP object stream in C#?

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.

like image 922
Neal Ehardt Avatar asked Nov 14 '22 22:11

Neal Ehardt


1 Answers

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.
like image 94
Alex Aza Avatar answered Dec 18 '22 04:12

Alex Aza