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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T00:56:17+00:00 2026-05-26T00:56:17+00:00

I have two TCP-server apps that are based on the same code, but for

  • 0

I have two TCP-server apps that are based on the same code, but for some reason exhibit different behavior and i’m ready to pull my hair out trying to figure out why. The code pattern is as follows:

public class TcpServer
{
    public static void Start( bool bService )
    {
        ..
        oTcpListnr= new TcpListener( ip, iOutPort );
        aTcpClient= new ArrayList( );
        bListen=    true;
        oTcpListnr.Start( );
        thOutComm=  new Thread( new ThreadStart( AcceptTcpConn ) );
        thOutComm.Name= "App-i.AcceptTcpConn";
        thOutComm.Start( );
        ..
    }
    public static void      Stop( )
    {
        bListen=    false;

        if(  thOutComm != null  )
        {
            thOutComm.Join( iTimeout );
            thOutComm=  null;
        }
        if(  oTimer != null  )
        {
            oTimer.Change( Timeout.Infinite, Timeout.Infinite );
            oTimer.Dispose( );
        }
    }
    public static void      AcceptTcpConn( )
    {
        TcpState    oState;
        Socket      oSocket=    null;

        while(  bListen  )
        {
            try
            {
        //      if(  oTcpListnr.Pending( )  )
                {
                    oSocket=    oTcpListnr.AcceptSocket( );
                    oState=     new TcpState( oSocket );

                    if(  oSocket.Connected  )
                    {
                        Utils.PrnLine( "adding tcp: {0}", oSocket.RemoteEndPoint.ToString( ) );
                        Monitor.Enter( aTcpClient );
                        aTcpClient.Add( oState );
                        Monitor.Exit( aTcpClient );

                        oSocket.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.DontFragment, true );
                        oSocket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.DontLinger, true );

            //  /       oSocket.BeginReceive( oState.bData, 0, oState.bData.Length, SocketFlags.None,   //  no need to read
            //  /                               new AsyncCallback( AsyncTcpComm ), oState );            //  for output only
                    }
                    else
                    {
                        Utils.PrnLine( "removing tcp: {0}", oSocket.RemoteEndPoint.ToString( ) );
                        Monitor.Enter( aTcpClient );
                        aTcpClient.Remove( oState );
                        Monitor.Exit( aTcpClient );
                    }
                }
        //      Thread.Sleep( iTcpWake );
            }
            #region catch
            catch( Exception x )
            {
                bool    b=  true;
                SocketException se= x as SocketException;
                if(  se != null  )
                {
                    if(  se.SocketErrorCode == SocketError.Interrupted  )
                    {
                        b=  false;
                        if(  oSocket != null  )
                            Utils.PrnLine( "TcpConn:\tclosing tcp: {0} ({1})", oSocket.RemoteEndPoint.ToString( ), se.SocketErrorCode );
                    }
                }
                if(  b  )
                {
                    Utils.HandleEx( x );
                }
            }
            #endregion
        }
    }
}

I omitted exception handling in Start/Stop methods for brevity. Variation in behavior is during program termination: one app shuts down almost immediately while the other gets stuck in oTcpListnr.AcceptSocket( ) call. I know that this is a blocking call, but in that case why does it not present an issue for the 1st app?

Usage of this class cannot be any simpler, e.g. for a command-line tool:

class   Program
{
    public static void  Main( string[] args )
    {
        TcpServer.Start( false );
        Console.Read( );
        Console.WriteLine( "\r\nStopping.." );
        TcpServer.Stop( );
        Console.WriteLine( "\r\nStopped.  Press any key to exit.." );
        Console.Read( );
    }
}

Whether any clients have connected or not does not make a difference, 2nd app always gets stuck.

I found a potential solution (commented lines) by checking TcpListener.Pending( ) prior to .AcceptSocket( ) call, but this immediately affects CPU utilization, therefore an inclusion of smth like Thread.Sleep(.) is a must. Altogether though I’d rather avoid this approach if possible, because of extra connection wait times and CPU utilization (small as it is).

Still, the main question is: what may cause the same exact code to execute differently? Both apps are compiled on .NET 4 Client Profile, x86 (32-bit), no specific optimizations. Thank you in advance for good ideas!

  • 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-26T00:56:18+00:00Added an answer on May 26, 2026 at 12:56 am

    Finally found the root cause: I missed a couple of important lines [hidden in a #region] in the Stop( ) method, which starts the ball rolling. Here’s how it should look:

    public static void      Stop( )
    {
            bListen=    false;
    
            if(  thOutComm != null  )
            {
                try
                {
                    oTcpListnr.Stop( );
                }
                catch( Exception x )
                {
                    Utils.HandleEx( x );
                }
                thOutComm.Join( iTimeout );
                thOutComm=  null;
            }
            if(  oTimer != null  )
            {
                oTimer.Change( Timeout.Infinite, Timeout.Infinite );
                oTimer.Dispose( );
            }
        }
    

    The call to TcpListener.Stop( ) kicks out the wait-cycle inside .AcceptSocket( ) with “A blocking operation was interrupted by a call to WSACancelBlockingCall” exception, which is then “normally ignored” (check for SocketError.Interrupted) by the code that i originally had.

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

Sidebar

Related Questions

I have two processes: a server that should be run in background, but starts
I have two databases on the same server with the same name and different
I have two insert statements, almost exactly the same, which run in two different
I have two programs written in C++ that use Winsock. They both accept TCP
I have two components that that communicate via TCP/IP. Component A acts as a
I have two applications written in Java that communicate with each other using XML
I have two named instances of SQL Server 2008 and am trying to set
I have a Java Client which sends UTF-8 strings to a C# TCP-Server, I'm
I have two arrays of animals (for example). $array = array( array( 'id' =>
I have two arrays of System.Data.DataRow objects which I want to compare. The rows

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.