Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8758569
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T14:34:58+00:00 2026-06-13T14:34:58+00:00

I want to use StreamReader and StreamWriter to receive and send data over TCPClient.NetworkStream.

  • 0

I want to use StreamReader and StreamWriter to receive and send data over TCPClient.NetworkStream. The code is depicted below:
Client code:

 using (TcpClient client = new TcpClient())
            {
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9001);
                client.Connect(localEndPoint);
                client.NoDelay = true;

                using(NetworkStream stream = client.GetStream())
                {                    
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        writer.AutoFlush = true;
                        using (StreamReader reader = new StreamReader(stream))
                        {    

                            string message = "Client says: Hello";
                            writer.WriteLine(message);

                // If I comment the line below, the server receives the  first message
                // otherwise it keeps waiting for data
                           string response = reader.ReadToEnd();
                           Console.WriteLine(response);
                        }
                       ;
                    }
                }
            }


Note: If I comment the reader.ReadToEnd(); then the server receives the message, otherwise the server keeps waiting for data from the client. Is ReadToEnd the problem?

Server code accepts a connection asynchronously, but handles the data in a synchronous manner:

class Program
    {
        private static AsyncCallback tcpClientCallback;
        static void Main(string[] args){

            IPEndPoint localEndPoint =  new IPEndPoint(IPAddress.Parse("127.0.0.1"),9001);
            TcpListener listener = new TcpListener(localEndPoint);

            listener.Start();

            tcpClientCallback = new AsyncCallback(ConnectCallback);
            AcceptConnectionsAysnc(listener);

            Console.WriteLine("Started Aysnc TCP listener, press any key to exit (server is free to do other tasks)");
            Console.ReadLine();
        }

        private static void AcceptConnectionsAysnc(TcpListener listener)
        {
            listener.BeginAcceptTcpClient(tcpClientCallback, listener);
        }

        static void ConnectCallback(IAsyncResult result)
        {
            Console.WriteLine("Received a conenct request");
            TcpListener listener = (TcpListener)result.AsyncState;

            // We are starting a thread which waits to receive the data
            // This is not exactly scalable
            Task recieveTask = new Task(() => { HandleRecieve(result, listener); });
            recieveTask.Start();

            AcceptConnectionsAysnc(listener);
        }


        // This makes a blocking call - that means until the client is ready to
        // send some data the server waits
        private static void HandleRecieve(IAsyncResult result, TcpListener listener)
        {
            Console.WriteLine("Waiting for data");

            using (TcpClient client = listener.EndAcceptTcpClient(result))
            {
                client.NoDelay = true;

                using (NetworkStream stream = client.GetStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.AutoFlush = true;
                            Stopwatch watch = new Stopwatch();
                            watch.Start();
                            string data = reader.ReadToEnd();
                            watch.Stop();
                            Console.WriteLine("Time: " + watch.Elapsed.TotalSeconds);
                            Console.WriteLine(data);


// Send a response to client
                                writer.WriteLine("Response: " + data);
                            }

                        }
                    }            


                }

            }

        } 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T14:34:59+00:00Added an answer on June 13, 2026 at 2:34 pm

    A stream doesn’t end until it is closed. Currently, both client and server are holding their connections open, and both is trying to read to the end from the other – and when they do, will close themselves. This is a deadlock: neither will ever get to the end, so neither will ever close (which would allow the other to get to the end).

    Options:

    • use raw sockets, and have the client close the outbound stream after sending:

      socket.Shutdown(SocketShutdown.Send);
      

      this lets the server read to completion, which lets the server close, which lets the client read to completion; the client can still read from the inbound stream after closing the outbound socket.

    • use a different termination metaphor than ReadToEnd; for text-based protocols, end-of-line is the most common (so: ReadLine); for binary protocols, a length-prefix of the message is the most common. This allows each end to read the next message, without ever having to read to the end of the stream. In this scenario it would only be a single message, but the strategy still works.

    • use a different protocol if you find the above tricky; http is good for single request/response operations, and can be handled at the server via HttpListener.

    Additionally, I’d be very careful about using ReadToEnd on a server (or even ReadLine) – that could be a good way of locking up threads on the server. If the server needs to cope with high throughput and lots of connections, async-IO based on raw sockets would be preferred.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i want simultaneously read and write data into file. Can i use StreamReader and
I want use this 1 for using Bar code or QR code scanner. I
I would like to write a program to receive some data using tcpClient from
i want use some data from a website with web service. i have a
I don't want use old Visual Basic methods in my code, and I'm confused
I am using the below string in my code : string AAR_FilePath = \C:\\MySQL\\MySQL
I currently use the following code to retrieve and decompress string data from Amazon
Because I'm using non-latin alphabet, if I use StreamWriter, the characters aren't correct. String
I want to unit test the code below. I've been working with MSTest and
I am trying to use StreamReader and StreamWriter to Open a text file (fixed

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.