Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a server socket is open on the other side

Tags:

java

sockets

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

like image 946
Mazzy Avatar asked Jan 15 '12 16:01

Mazzy


People also ask

How do I know if a server socket is closed?

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.

How can I check my socket status?

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.

What is the socket on the server side?

The server socket serves as an endpoint that TCP clients such as the client illustrated in client1. c can connect to.

Can server open socket client?

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.


2 Answers

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.

like image 134
Sanjay T. Sharma Avatar answered Oct 05 '22 10:10

Sanjay T. Sharma


If the server is not listening you will get an Connection Refused in an exception. You will never get a null from a new

like image 45
Peter Lawrey Avatar answered Oct 05 '22 10:10

Peter Lawrey