How do I know if a socket is "listening" on the server side?

Asked

Viewed 244 times

3

When I use the function isConnected() of java.net.Socket, on the client’s side, and she returns to me true can I make sure the server is "listening"? How else can I know? Only with a waiting time between connecting and starting "writing"?

PS: I put the tag Android because I do not know if it has influence.

  • 1

    I cannot say, but perhaps this is related https://answall.com/a/45393/3635

  • @Guilhermenascimento I just want to know if the server is reading what I write in the socket before I start writing.

  • 1

    So, just using the Socket API simply doesn’t have a way. The client may have disconnected and not notified the Socket, and the server doesn’t know. One technique I usually use is Heart Beat, which is to send specific opaque packets, just to see if it arrives. If the answer doesn’t come, we can assume the other side of Socket is dead*.

  • Yes, so I quoted the answer, maybe I can’t be sure and so the answer suggests things like a "timer", but when it comes to "persistent communication", maybe I have a way of knowing, of course I would say that the customer would need to keep sending a signal "constant".

  • @Wakim is the other way around. I want to know if the server is "reading" what I send.

  • But in this case if you send and fail you know that the server is not accessible. But do you want to check this first? Ai has to "ping" it to check availability.

  • @Wakim the harm is that I don’t have this feature. But thanks for the tips.

  • So Jorge, one possibility is to use the ICMP protocol to run a ping on the server, it would be something similar to a terminal ping, it may be the simplest way, unless the server is blocking the port :( Looking more calmly, it seems that the class InetAddress provides this functionality through the method isReachable, it performs a ping on the server (remembering that it may be blocked yet).

  • 2
Show 4 more comments

1 answer

2

Good night Jorge,

As the documentation says: Note: Closing a socket doesn’t clear its Connection state, which Means this method will Return true for a closed socket (see isClosed()) if it was successfuly Connected prior to being closed.

When a socket connection closes it does not change the state of the object, so it remains true.

The best approach is for you to implement an ACK in your client/server. Your client performs an ACK for your server and responds. If an error occurs in writing the socket you know that the connection has been lost and connects again.

Abs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.