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 8973667
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T18:30:00+00:00 2026-06-15T18:30:00+00:00

I am trying to have a server allow TCP connections and and echo out

  • 0

I am trying to have a server allow TCP connections and and echo out any newline delimited messages being sent. I want multiple clients to be able to connect one after another, maintaining the same server socket. Here’s my code:

TcpClient client;

while (true) {
    Console.Write("Waiting for connection... ");
    client = listener.AcceptTcpListener();
    nStream = client.GetStream();
    sReader = new StreamReader(nStream);
    Console.WriteLine("Connected!");

    while (client.Connected) {
        string line = sReader.ReadLine();
        Console.WriteLine(line);
    }
    Console.WriteLine("#Client Disconnected")
}

Unfortunately, when the remote client disconnects, it never escapes the “while (client.Connected)” loop. Instead I get an infinite write to STDOUT.

  • 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-15T18:30:01+00:00Added an answer on June 15, 2026 at 6:30 pm

    Basically, the property that you’re using TcpClient.Connection does not do what you think it does. From the MSDN documentation:

    http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.connected.aspx

    Because the Connected property only reflects the state of the connection as of the most recent operation, you should attempt to send or receive a message to determine the current state. After the message send fails, this property no longer returns true. Note that this behavior is by design. You cannot reliably test the state of the connection because, in the time between the test and a send/receive, the connection could have been lost.

    The gist is that the property TcpClient.Connection was not updated after the host disconnected but before your server blocked waiting to read another line from the stream. You need a more reliable way to detect if the connection is active before you block.

    Turns out, this question has been asked before. So, I borrowed the answer from here and adapted it to the format that you’re using in the OP.

    https://stackoverflow.com/a/8631090

        static void Main(string[] args)
        {
            TcpClient client = new TcpClient();
            TcpListener listener = new TcpListener(IPAddress.Loopback, 60123);
            listener.Start();
    
            while (true)
            {
                Console.WriteLine("Waiting for connection...");
                client = listener.AcceptTcpClient();
                Console.WriteLine("Connection found");
                StreamReader reader = new StreamReader(client.GetStream());
    
                string line = string.Empty;
                while (TestConnection(client))
                {
                    line = reader.ReadLine();
                    Console.WriteLine(line);
                }
                Console.WriteLine("Disconnected");
            }
        }
    
        private static bool TestConnection(TcpClient client)
        {
            bool sConnected = true;
    
            if (client.Client.Poll(0, SelectMode.SelectRead))
            {
                if (!client.Connected) sConnected = false;
                else
                {
                    byte[] b = new byte[1];
                    try
                    {
                        if (client.Client.Receive(b, SocketFlags.Peek) == 0)
                        {
                            // Client disconnected
                            sConnected = false;
                        }
                    }
                    catch { sConnected = false; }
                }
            }
            return sConnected;
        }
    

    This works for me when I test it, and the reason that it works is that you cannot tell if the connection is closed until you attempt to read or write from it. You can do that by blindly trying to read/write and then handling the IO exceptions that come when the socket is closed, or you can do what this tester method is doing and peek to see if the connection is closed.

    Hope this helps you

    EDIT:

    It should be noted that this may or may not be the most efficient way to check if the connection is closed, but it is purely to illustrate that you must check the connection yourself on the server side by reading/writing instead of relying on TcpClient.Connection.

    EDIT 2:

    My sample doesn’t clean up old resources very well, apologies to anyone who had an OCD reaction.

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

Sidebar

Related Questions

I am trying out GWT in this 'configuration': 1) I have written a server
I'm trying to allow multiple connections to a little Java server type app. It
I have a server that has several virtual machines running on it. I'm trying
I am trying to have a client and server talk to each other using
I am trying to have a simple java server respond to an XmlHttpRequest, but
I have the SQL Server 2005 Developer Edition DVD. I have been trying to
We installed the django toolbar yesterday on our remote server and have been trying
I have been trying to defrag indexes in SQL Server 2005 and nothing seems
I have a bluehost server setup and am trying to set the path in
i have a sql server that i use and i am trying to code

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.