jgallant
jgallant

Reputation: 11273

Multiple NetworkStreams for each client

I have recently started getting into NetworkStreams, and I had a question. I am currently creating a thread, and processing all incoming messages as they come in.

Here is the code to illustrate this:

client.Connect(serverEndPoint);
clientStream = client.GetStream();
client.NoDelay = true;

ctThread = new Thread(getMessage);
ctThread.Start();  

private void getMessage()
{
    while (true)
    {
        Byte[] data = new Byte[800];
        String responseData = String.Empty;
        Int32 bytes = clientStream.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);

        MessageReceived(this, new ClientMessageEventArgs(responseData));
    }
}

In the above, I raise an event "MessageReceived" which is handled according the the packet data. This works great, but also have a seperate case where I need to retrieve data immediately after I send my request.

Is it ok to have two streams per client? Is this even possible to do on the same port? How should this be handled? Essentially, I want to be able to Send and then Receive data immediately after (blocking way).

Upvotes: 0

Views: 444

Answers (1)

MarcF
MarcF

Reputation: 3299

You can read and write from network streams independently and in a thread safe manner. i.e. reading from one thread and writing from another.

If you checkout the open source network communication library networkComms.net you can see how this is achieved independently in the sending method SendPacket() (line 1304) and receiving method IncomingPacketHandler() (line 802).

Mx

Upvotes: 1

Related Questions