I would check if a server socket placed in the server is open. In the client when I create the socket Socket sock = new Socket(host,port)
I check if it's open doing:
if(sock == null)
System.out.println("The server is not connected!");
else
//Doing some task
but i don't receive any result. there is method to check if the server socket at on the other side is open? I tried even the method isConnected()
but nothing
The only way to tell if the socket has been disconnected is to send data over it. set the timeout on the server side socket and then have the client check in every so often within the timeout so if you set the client to check in every 10 seconds then set the timeout to say 30 seconds on the server socket.
There is an easy way to check socket connection state via poll call. First, you need to poll socket, whether it has POLLIN event. If socket is not closed and there is data to read then read will return more than zero. If socket is closed then POLLIN flag will be set to one and read will return 0.
The server socket serves as an endpoint that TCP clients such as the client illustrated in client1. c can connect to.
Create a Socket server To create the server socket, the endPoint object can listen for incoming connections on any IP address but the port number must be specified. Once the socket is created, the server can accept incoming connections and communicate with clients.
The simplest way to check reachability and liveness is to create a blank Socket
and use the connect()
method with a reasonable timeout. I wrote a similar answer with a small code snippet here.
If the server is not listening you will get an Connection Refused in an exception. You will never get a null from a new
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With