none
TcpClient - Check IsConnected RRS feed

  • Question

  • Hello,

    There are so many possibilities and no clear directive.

    // This works better
    public bool IsConnected2()
    {
    	var qry = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections().SingleOrDefault(x => x.LocalEndPoint.Equals(TClient.Client.LocalEndPoint));
    
    	if (qry == null)
    	{
    		Log.Debug("IsConnected_04 is null");
    		return false;
    	}
    
    	bool ret = false;
    
    	TcpState tcpState = qry.State;
    	switch (tcpState)
    	{
    		default:
    			ret= false;
    			break;
    		case TcpState.Established:
    			ret = true;
    			break;                    
    	}
    	Log.Debug($"IsConnected_04 state= '{tcpState}'     ret= '{ret}'");
    	return ret;
    }
    
    public bool IsConnected_NotWorking()
    {
    	bool ret = true;
    	if (TClient.Client.Poll(0, SelectMode.SelectRead))  // True if, connection closed
    	{
    		byte[] buff = new byte[1];
    
    		int t = TClient.Client.Receive(buff, SocketFlags.Peek); 
    		// What should I received, when connection is closed?
    		if (t== 0)
    		 ret = false;
    	}
    	return ret;
    }
    
    
    //~~~~~~
      TClient = new TcpClient();
    Maybe I need a eventhandler to give me the state of connection and inform me about disconnection.
    Is not available in this class.
    How is your opinion?
    Do you have a clear guideline?
    Thanks in advance.
    With best regards Markus

    Friday, February 1, 2019 4:20 PM

Answers


  • Hi Markus Freitag,   

    >> Maybe you still have a universal solution.

    IsConnected, this property should be modified behind the code.

    When a client initiates a connection to a server, the server has received data and therefore calls the socket "connected." 

    You can keep clients on your server side and send heartbeat detection client is connected status Timely(Thread). 

    The suitable way you know that the client is no longer available (e.g. disconnected) is that you try to send data to it and after some predetermined time (we call those timeouts) fail to get any kind of response.

    If it is disconnected, disconnect and release resources. There is no ready-made code, you need to try on your side.

    Best Regards,

    Yong Lu

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Markus Freitag Monday, February 11, 2019 5:28 PM
    Monday, February 11, 2019 3:12 AM
    Moderator

All replies

  • It's somewhat unusual to need this information.  Why do you want it?  Usually, you just keep reading on the socket until you get an error back, and that's when you know the connection dropped.  It's not like there's a switch that gets thrown when a connection drops.  You just stop getting responses.

    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Friday, February 1, 2019 10:03 PM
  • Hello Tim,

    I send a request, at this moment the server may have been closed, then I have to reconnect.

    Idea.

       Check the current state, if not TcpState.Established

                       make a reconnect.

    That is it.

    Every time the same, Request - Client, Response - Server.

    Have you a good solution? Thanks in advance.

    Many greetings Markus


    Saturday, February 2, 2019 11:45 AM
  • Hello Tim,

    I send a request, at this moment the server may have been closed, then I have to reconnect.

    Idea.

       Check the current state, if not TcpState.Established

                       make a reconnect.

    That is it.

    Every time the same, Request - Client, Response - Server.

    Have you a good solution? Thanks in advance.

    Many greetings Markus


    Hi Markus Freitag,

    You can add Heartbeat handshake to detect disconnection from server socket.

    The following links for your reference.

    TCPListener how to detect client socket disconnected


    How to detect disconnection from server socket?


    Best Regards,

    Yong Lu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, February 4, 2019 3:13 AM
    Moderator

  • TCPListener how to detect client socket disconnected


    How to detect disconnection from server socket?


    Hi Yong Lu,

     if (!Socket.Poll(0, SelectMode.SelectRead) && Socket.Available == 0)
                {
                    // Socket is available 
                }
                else
                {
                  // Socket Has been closed
                 }

    I tried, did not work. For whatever reason. The topic is big and no one really knows. Is there really no general valid solution? That need several people.

    Request - Response - Synchron

    Maybe I would have to solve it event-oriented? Maybe the simpler solution of the synchronous implementation does not work.

    Maybe you still have a universal solution.

    IsConnected, this property should be modified behind the code.

    Many greetings Markus

    Monday, February 4, 2019 11:02 AM
  • For context here is the previous thread.

    Michael Taylor http://www.michaeltaylorp3.net

    Monday, February 4, 2019 2:51 PM
    Moderator
  • For context here is the previous thread.


    Hello Michael,

    Right.

    public bool IsConnected2()

    As I said, I just want to know how to solve it correctly.

    If nobody knows, I use my solution. As I see it, that works.

    Greetings Markus

    Monday, February 4, 2019 5:11 PM
  • As you know Markus, I've been advocating event-oriented TCP (my blog for anyone interested: http://geek-goddess-bonnie.blogspot.com/2018/12/event-driven-tcp.html ).

    But, since you're not using an event-driven methodology and your solution works, I don't see any reason to try something different. As long as you've fully tested it and are sure there aren't any problems with it.


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Thursday, February 7, 2019 4:27 PM
    Moderator
  • As you know Markus, I've been advocating event-oriented TCP (my blog for anyone interested: http://geek-goddess-bonnie.blogspot.com/2018/12/event-driven-tcp.html ).

    But, since you're not using an event-driven methodology and your solution works, I don't see any reason to try something different. As long as you've fully tested it and are sure there aren't any problems with it.



    Hello Bonnie,

    I know, but now I need only a synchron communication.

    With best regards  Markus

    Thursday, February 7, 2019 5:43 PM

  • Hi Markus Freitag,   

    >> Maybe you still have a universal solution.

    IsConnected, this property should be modified behind the code.

    When a client initiates a connection to a server, the server has received data and therefore calls the socket "connected." 

    You can keep clients on your server side and send heartbeat detection client is connected status Timely(Thread). 

    The suitable way you know that the client is no longer available (e.g. disconnected) is that you try to send data to it and after some predetermined time (we call those timeouts) fail to get any kind of response.

    If it is disconnected, disconnect and release resources. There is no ready-made code, you need to try on your side.

    Best Regards,

    Yong Lu

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Markus Freitag Monday, February 11, 2019 5:28 PM
    Monday, February 11, 2019 3:12 AM
    Moderator
  • This is NOT a good test for socket being closed. You can run into a race condition where Poll returns true for data is available for reading, but Available says 0 bytes. You need further tests to verify the socket is actually closed. You could try repeating the IF statement once. I suspect there is a better solution.
    Thursday, April 25, 2019 6:52 PM