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

  • Home
  • SEARCH
  • 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 7071455
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T05:41:24+00:00 2026-05-28T05:41:24+00:00

I’ve both a client and a server communicating through TCP. The client uses the

  • 0

I’ve both a client and a server communicating through TCP.
The client uses the NetworkStream to send info to the server that reads it back, then the process continues until the user wants to exit and close the connection. The problem is that the NetworkStream is dirty with a previous write. So let’s suppose the client sends the string “aa “during the first time, and “b” during the second. On the second read the server will get “ba”. What’s missing here? Shouldn’t the NetworkStream be consumed during the server reads? Here`s the relevant code …

Server

        while (true)
        {
            try
            {
                NetworkStream clientStream = tcpClient.GetStream();
                bytesRead = clientStream.Read(messageBytes, 0, messageBytes.Length);
            }
            catch (Exception ex)
            {
                LogToConsole(clientEndPoint, String.Format("[ERROR] Exception: {0}", ex.Message));
                break;
            }

            if (bytesRead == 0)
            {
                LogToConsole(clientEndPoint, "Client has disconnected");
                break;
            }

            messageCounter++;
            string message = Encoding.ASCII.GetString(messageBytes);
            message = message.Substring(0, message.IndexOf('\0'));
            LogToConsole(clientEndPoint, String.Format(" >> [{0}] Message received: {1}", messageCounter, message));
        }

CLIENT

            string infoToSend = null;
            do
            {
                Console.Write(" >> Info to send: ");
                infoToSend = Console.ReadLine();

                if (!String.IsNullOrEmpty(infoToSend))
                {
                    NetworkStream serverStream = client.GetStream();
                    byte[] buffer = Encoding.ASCII.GetBytes(infoToSend);
                    serverStream.Write(buffer, 0, buffer.Length);
                    serverStream.Flush();
                }
            } while (!String.IsNullOrEmpty(infoToSend));

SOLUTION

As Douglas spotted, the buffer (messageBytes) was dirty with a previous read. I ended up with this code for the server (I posted the entire code as it might be useful for somebody else):

namespace Gateway
{
    class Program
    {
        static void Main(string[] args)
        {
            int requestCount = 0;

            TcpListener serverSocket = new TcpListener(IPAddress.Any, 8888);
            serverSocket.Start();
            LogToConsole("Server Started. Waiting for clients ...");

            while ((true))
            {
                try
                {
                    TcpClient client = serverSocket.AcceptTcpClient();
                    requestCount++;
                    LogToConsole(String.Format("Connection from {0} accepted. Request #{1}", client.Client.RemoteEndPoint.ToString(), requestCount));

                    Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientConnection));
                    clientThread.IsBackground = true;
                    clientThread.Start(client);
                    LogToConsole(String.Format("Thread #{0} created to handle connection from {1}", clientThread.ManagedThreadId, client.Client.RemoteEndPoint.ToString()));
                    LogToConsole("Waiting for next client ...");
                }
                catch (Exception ex)
                {
                    LogToConsole(ex.ToString());
                    break;
                }
            }
        }

        static void HandleClientConnection(object client) 
        {
            TcpClient tcpClient = (TcpClient)client;

            byte[] messageBytes = new byte[1024];
            int bytesRead;
            int messageCounter = 0;

            string clientEndPoint = tcpClient.Client.RemoteEndPoint.ToString();

            while (true)
            {
                try
                {
                    NetworkStream clientStream = tcpClient.GetStream();
                    bytesRead = clientStream.Read(messageBytes, 0, messageBytes.Length);
                }
                catch (Exception ex)
                {
                    LogToConsole(clientEndPoint, String.Format("[ERROR] Exception: {0}", ex.Message));
                    break;
                }

                if (bytesRead == 0)
                {
                    LogToConsole(clientEndPoint, "Client has disconnected");
                    break;
                }

                messageCounter++;
                string message = Encoding.ASCII.GetString(messageBytes, 0, bytesRead);
                LogToConsole(clientEndPoint, String.Format(" >> [{0}] Message received: {1}", messageCounter, message));
            }

            LogToConsole(clientEndPoint, "Closed connection to client");
            tcpClient.Close();
        }

        static void LogToConsole(string clientEndPoint, string message)
        {
            int threadId = Thread.CurrentThread.ManagedThreadId;
            string time = DateTime.Now.ToString("HH:mm:ss");
            Console.WriteLine("{0} [{1}, {2}] {3}", time, threadId, clientEndPoint, message);
        }

        static void LogToConsole(string message)
        {
            int threadId = Thread.CurrentThread.ManagedThreadId;
            string time = DateTime.Now.ToString("HH:mm:ss");
            Console.WriteLine("{0} [{1}] {2}", time, threadId, message);
        }
    }
}
  • 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-05-28T05:41:24+00:00Added an answer on May 28, 2026 at 5:41 am
    string message = Encoding.ASCII.GetString(messageBytes);
    

    The above call decodes the entire buffer each time, despite that each message would only be written to the first n bytes of it (where n is the message length). Your first message, “aa”, is written to the first two bytes of the buffer. Your second message, “b”, is written to just the first byte, overwriting the first ‘a’ character but leaving the second ‘a’ intact. This is why the buffer appears to contain “ba” after your second message.

    You can trivially solve this by changing the call above to:

    string message = Encoding.ASCII.GetString(messageBytes, 0, bytesRead);
    

    However, your code would still be susceptible to another issue: NetworkStream.Read only reads as much data as is currently available. If the client is still transmitting, then it might return a partial message. So your server might read the two messages as “a” and “ab”.

    In your case, since you seem to be transmitting single-line text messages only, you could wrap the NetworkStream in a StreamReader in the server, and in a StreamWriter in the client. Then, simply call StreamReader.ReadLine on the server, and StreamWriter.WriteLine on the client. ReadLine will keep reading until it encounters a newline, and will return null when the end of the stream is reached.

    Server:

    using (NetworkStream clientStream = tcpClient.GetStream())
    using (StreamReader reader = new StreamReader(clientStream))
    {
        while (true)
        {
            message = reader.ReadLine();
    
            if (message == null)
            {
                LogToConsole(clientEndPoint, "Client has disconnected");
                break;
            }
    
            messageCounter++;
            LogToConsole(clientEndPoint, String.Format(" >> [{0}] Message received: {1}", messageCounter, message));
        }
    }
    

    Client:

    using (NetworkStream serverStream = client.GetStream())
    using (StreamWriter writer = new StreamWriter(serverStream))
    {
        do
        {
            Console.Write(" >> Info to send: ");
            infoToSend = Console.ReadLine();
    
            if (!String.IsNullOrEmpty(infoToSend))
                writer.WriteLine(infoToSend);
    
        } while (!String.IsNullOrEmpty(infoToSend));
    }
    

    This solution will not work if your client can send newlines within your messages.

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

Sidebar

Related Questions

I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I am currently running into a problem where an element is coming back from
I need a function that will clean a strings' special characters. I do NOT
I am writing an app with both english and french support. The app requests
I'm trying to create an if statement in PHP that prevents a single post

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.