determine if Socket is connected

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • semedao

    determine if Socket is connected

    Hi all,
    I view many posts about this issue , the connected property does not tell us the current status of the socket.

    based on couple of suggestions of msdn , and some article here , I try to write an helper method that will tell if the socket is connected or not , but it's not working good
    continue to tell me that the socket is connectedeven if the other party already call shutdown(both) + close , or , even if the other party close the app itslef.
    also I determine different behaviour when my app running behind NAT
    when I run behind NAT , calling to socket.Receive( ..) throw exception which was good forme to determine that it's already closed the connection , it doesn't throw nothing when I run the same code without NAT

    Here is my code:

    /// <summary>

    /// Determine if the givven socket is connected or not

    /// </summary>

    /// <remarks>

    /// There is a problem to based the Socket.Connecte d property since it's show the last operaion status: (from msdn)

    /// The Connected property gets the connection state of the Socket as of the last I/O operation. When it returns false, the Socket was either never connected, or is no longer connected.

    /// The value of the Connected property reflects the state of the connection as of the most recent operation. If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.

    /// </remarks>

    /// <seealso cref="http://groups.google.c om/group/microsoft.publi c.dotnet.langua ges.csharp/browse_thread/thread/3cf03e064173165 9/76e2563d28f1b25 6?lnk=st&q=c%23 +determine+if+s ocket+connected &rnum=5#76e2563 d28f1b256"/>

    /// <seealso cref="http://windowssdk.msdn .microsoft.com/en-us/library/system.net.sock ets.socket.conn ected.aspx"/>

    /// <returns>Bool , True if connected , False if not</returns>

    public static bool IsConnected(Soc ket checkSocket)

    {

    try

    {

    //if (checkSocket.Ge tSocketOption(S ocketOptionLeve l.Socket, SocketOptionNam e.KeepAlive, 1)[0].Equals(1))

    // return checkSocket.Con nected;

    if (checkSocket.Co nnected == false)

    return false;

    //checkSocket.Beg inSend(new byte[0], 0, 0, SocketFlags.Non e, null, null);

    bool bSelectRead = checkSocket.Pol l(1, SelectMode.Sele ctRead);

    bool bSelectWrite = checkSocket.Pol l(1, SelectMode.Sele ctWrite);

    int available = checkSocket.Ava ilable;

    //if (bSelectWrite && bSelectRead && available 0)

    if (bSelectWrite && bSelectRead)

    {

    //return true;

    //checkSocket.Beg inReceive(new byte[1], 0, 1, SocketFlags.Pee k, null, null);

    checkSocket.Rec eive(new byte[0], 0, 0, SocketFlags.Pee k);

    checkSocket.Sen d(new byte[0], 0, 0, SocketFlags.Non e);

    return checkSocket.Con nected;

    }

    else

    return false;

    }

    catch (SocketExceptio n)

    {

    return false;

    }

    catch (ObjectDisposed Exception)

    {

    return false;

    }

    }





    here is MS code , that also don't work - tell that the socket is connected even if the other party already close...

    // This is how you can determine whether a socket is still connected.
    bool blockingState = client.Blocking ;
    try
    {
    byte [] tmp = new byte[1];

    client.Blocking = false;
    client.Send(tmp , 0, 0);
    Console.WriteLi ne("Connected!" );
    }
    catch (SocketExceptio n e)
    {
    // 10035 == WSAEWOULDBLOCK
    if (e.NativeErrorC ode.Equals(1003 5))
    Console.WriteLi ne("Still Connected, but the Send would block");
    else
    {
    Console.WriteLi ne("Disconnecte d: error code {0}!", e.NativeErrorCo de);
    }
    }
    finally
    {
    client.Blocking = blockingState;
    }

    Console.WriteLi ne("Connected: {0}", client.Connecte d);


  • semedao

    #2
    Re: determine if Socket is connected

    So... this method is something many developers need , there are noting in
    ..NET that already do it ?
    "Vadym Stetsyak" <vadym_s@ukr.ne twrote in message
    news:uo$1dhX3GH A.2152@TK2MSFTN GP06.phx.gbl...
    Hello, semedao!
    >
    sbased on couple of suggestions of msdn , and some article here , I try
    sto write an helper method that will tell if the socket is connected or
    snot , but it's not working good continue to tell me that the socket is
    sconnectedeven if the other party already call shutdown(both) + close ,
    sor , even if the other party close the app itslef.
    >
    Until there is no network I/O you can't get peer's socket state.
    >
    salso I determine different behaviour when my app running behind NAT
    when I
    srun behind NAT , calling to socket.Receive( ..) throw exception which
    was
    sgood forme to determine that it's already closed the connection , it
    sdoesn't throw nothing when I run the same code without NAT
    >
    When you're behind NAT, NAT server can detect peer state and send you
    RST packet that will notify that socket is not connected anymore.
    >
    [skipped]
    >
    There are following ways how to resolve:
    - use SocketOptionNam e.KeepAlive
    - develop custom keep-alive mechanism.
    >
    --
    Regards, Vadym Stetsyak
    www: http://vadmyst.blogspot.com

    Comment

    • Vadym Stetsyak

      #3
      Re: determine if Socket is connected

      Hello, semedao!

      sSo... this method is something many developers need , there are noting
      sin .NET that already do it ?

      If you're using plain sockets you have to do it yourself.

      In order to make keep-alives work, specify KeepAliveTime and KeepAliveInterv al
      under windows registry
      ( http://support.microsoft.com/default...b;en-us;158474 ).
      Computer restart may be required.

      --
      Regards, Vadym Stetsyak
      www: http://vadmyst.blogspot.com

      Comment

      • Mike Blake-Knox

        #4
        Re: determine if Socket is connected

        In article <ODpi1sX3GHA.50 40@TK2MSFTNGP02 .phx.gbl>, Semedao wrote:
        So... this method is something many developers need , there are noting in
        ..NET that already do it ?
        Semedao,

        It's one of those yes and no situations. The Socket.Connecte d property tells
        you if the local socket knows it's connected to the other end.
        Unfortunately, the socket doesn't always know if it's connected due to the
        way the TCP protocol is designed. The socket also only updates its
        open/closed state when a Send or Receive operation is performed (see

        _members.aspx). If you search this newsgroup, you'll find many threads
        addressing this isuue.

        Mike

        Comment

        • Charles Wang[MSFT]

          #5
          RE: determine if Socket is connected

          Hi,
          This is Charles from Microsoft Online Community Support. For this issue, I
          noticed that Vadym and Mike had given you explanations. I think the replies
          are reasonable. If you wanted to know exactly the connection status, I'm
          afraid that you need to judge according to socket exception when you send
          or receive data on the socket.

          Could you please let me know the issue status and if you need further
          research? If you have any other questions or concerns, please feel free to
          let me know. It's my pleasure to be of assistance.

          Sincerely,
          Charles Wang
          Microsoft Online Community Support

          Comment

          • semedao

            #6
            Re: determine if Socket is connected

            I understand this issue , so the only way is to inherit the socket and
            override the send & receive method to throw some event of
            connected/disconnected
            thanks
            "Charles Wang[MSFT]" <changliw@onlin e.microsoft.com wrote in message
            news:cVOdnvv4GH A.4344@TK2MSFTN GXA01.phx.gbl.. .
            Hi,
            This is Charles from Microsoft Online Community Support. For this issue, I
            noticed that Vadym and Mike had given you explanations. I think the
            replies
            are reasonable. If you wanted to know exactly the connection status, I'm
            afraid that you need to judge according to socket exception when you send
            or receive data on the socket.
            >
            Could you please let me know the issue status and if you need further
            research? If you have any other questions or concerns, please feel free to
            let me know. It's my pleasure to be of assistance.
            >
            Sincerely,
            Charles Wang
            Microsoft Online Community Support
            >

            Comment

            • Charles Wang[MSFT]

              #7
              Re: determine if Socket is connected

              Hi,
              Appreciate your understanding and updating on this issue.

              If you have any other questions or concerns, please feel free to let me
              know. It's always my pleasure to be of assistance.

              Sincerely,
              Charles Wang
              Microsoft Online Community Suppport

              Comment

              • Mike Blake-Knox

                #8
                Re: determine if Socket is connected

                In article <e5QTxq74GHA.12 56@TK2MSFTNGP04 .phx.gbl>, Semedao wrote:
                so the only way is to inherit the socket and
                override the send & receive method to throw some event of
                connected/disconnected
                You don't need to override the Send and Receive methods to have errors
                reported as events. The base methods already raise socket exceptions
                (etc.). What you do want to do is to ensure that your application has
                a receive outstanding when you want to detect problems. When a simple,
                synchronous (server) application has finished processing one request,
                it naturally uses the Receive mthod to get the next request so error
                exceptions are raised at this point.

                Mike

                Comment

                Working...