How to check if server connection exists? - java

In my app I have asyncTask classes, that connects to a local/remote server to get some data, I want to check the server connection before the asyncTask runs,
I have this function:
public static boolean checkServerAvailable(String hostURL) {
HttpURLConnection connection = null;
try {
URL u = new URL(hostURL);
connection = (HttpURLConnection) u.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("HEAD");
int code = connection.getResponseCode();
System.out.println("" + code);
return true;
// You can determine on HTTP return code received. 200 is success.
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
This function uses timeout to connect to server, and if the timeout expires it means that there is no server. The problem is that I'm run this code and it's returning "there is no server" even if the server exists.
I've tried to set a big timeout like 5000ms but it pauses the UI very long time, and sometimes still returns "there is no server" even when the server is exist.
what can I do?
Thank you!

check the server connection before the asyncTask runs
Then you have to do that in another AsyncTask.
So this all makes little sense.
You are not using StrictMode is it?

try using socket here is example code
Socket socket;
final String host = "your.server.IP.or.host";
final int port = 80;
final int timeout = 5000; // 5 seconds or what ever time you want
try {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), timeout);
}
catch (UnknownHostException uhe) {
Log.e("ServerSock", "I couldn't resolve the host you've provided!");
}
catch (SocketTimeoutException ste) {
Log.e("ServerSock", "After a reasonable amount of time, I'm not able to connect, Server is probably down!");
}
catch (IOException ioe) {
Log.e("ServerSock", "Hmmm... Sudden disconnection, probably you should start again!");
}

Related

How do I close any previous Bluetooth sockets after my app starts?

In my app, I open and close a Bluetooth socket on the same device each session and listen for data. When I close one, I make sure to close the input and output streams and then socket in a cancel method. Still, for some people the app keeps trying to read from the device. I know because I read logs that are from run() in the listening thread, where there is a flag for listening that's set to false in cancel, and the listening thread will end when the socket is closed due to an IOException, but this never happens, so the socket must still be opened. I see logs of attempted reads every second of every day even though the person isn't using the app. This might be because the app crashes and the cancel method isn't called. Either way I can't guarantee the cancel method will be called. How do I close any Bluetooth sockets that were previously opened when I start up my app, if these were all opened in new threads created independently?
This guy had the same problem but I didn't see any solution:
Android bluetooth connection doesn't close after application crash
The accepted answer is no good because:
The current users haven't had the UncaughtExceptionHandler run that code yet and they need to have any previous connections closed when the new version is released
The UncaughtExceptionHandler must have a reference to the sockets, which it doesn't have. I want to be able to close any Bluetooth sockets when the app starts.
The guy who made that question asked how to get information about the socket to store for when the app starts up and you want to close them, and got no response.
EDIT:
How I open the socket (removed logging code):
try {
tmp.connect();;
} catch (IOException e) {
isConnected = false;
try {
tmp = (BluetoothSocket) device.getClass().getMethod("createRfcommSocket",
new Class[] {int.class}).invoke(device, 1);
} catch (Exception e2) {
e2.printStackTrace();
}
try {
tmp.connect();
setConnected();
} catch (IOException e1) {
e1.printStackTrace();
isConnected = false;
cancel();
}
How I close the socket:
public void cancel() {
isConnected = false;
listening = false;
try {
if (manageConnection.mmInStream != null) {
manageConnection.mmInStream.close();
manageConnection.mmInStream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (manageConnection.mmOutStream != null) {
manageConnection.mmOutStream.close();
manageConnection.mmOutStream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
mmSocket.close();
mmSocket = null;
manageConnection = null;
} catch (IOException e) {
// Logging code
}
}
}
Listening:
while (listening == true) {
try {
synchronized (ListeningActivity.lock) {
buffer = new byte[mmInStream.available()];
mmInStream.read(buffer);
....
} catch (IOException e) {
// Code that calls cancel()

Checking Database Server Status with Java

I want to check the online/offline status about a Database Server with Java.
Can I check this with a Socket connection over the port? I want to do this wihtout a Database connection with jdbc because the login and Database system info is unknown.
You can try the following:
try {
Socket socket = new Socket("127.0.0.1", port); //Port dependent on your DB/Server
// Server is up
socket.close();
}
catch (IOException e)
{
// Server is down
}
Yes, you can just open a Socket to the address and port of your databse server, if you get an IOException the server is down. (tested with postgress)
public boolean isDatabaseOnline(String address, int port) {
boolean result;
try {
Socket socket = new Socket(address, port);
socket.close();
result = true;
} catch (IOException e) {
result = false;
}
return result;
}
The above approaches don't really consider timing out in case the remote is unreachable, and a reasonable timeout should be defined because the default value is 20 seconds!!
You can state a timeout using the socket.connect method AFTER you create a blank socket.
SocketFactory sf = SocketFactory.getDefault();
try (Socket socket = sf.createSocket()) {
socket.connect(new InetSocketAddress(ipAdder, port), timeoutInMillis);
logger.info("database is up");
} catch (IOException e) {
logger.info("database is down");
}
The example above uses try with resources

How to code retry policy for port in server side to listen client request?

I am writing HTTP WEB SERVER code. In the mean while I have to code retry policy on using port, so that on that port server can listen client's request.
Normal Code:
serversocket = new ServerSocket(ServerSettings.port);
It throws Exception, if ServerSettings.port is not free.
Now, I want to add retry policy, if ServerSettings.port is not free, try other ports. For that I write one code, and code is a s follows,
Updated Code:
try {
serversocket = new ServerSocket(ServerSettings.port);
} catch (IOException io) {
try {
ServerSettings.port += 505;
serversocket = new ServerSocket(ServerSettings.port);
} catch (IOException io1) {
try {
ServerSettings.port += 505;
serversocket = new ServerSocket(ServerSettings.port);
} catch (IOException io2) {
log.info(new Date() + "Problem occurs in binding port");
}
}
}
But above one shows poor coding skills, and not professional one.
How can I write retry policy for ports in a professional way, so that server can listen on that port?
Logically, I think this will work (Correct me if there are any syntax typos):
ServerSocket serversocket;
boolean foundPort = false;
while (!foundPort)
{
try {
serversocket = new ServerSocket(ServerSettings.port); // If this fails, it will jump to the `catch` block, without executing the next line
foundPort = true;
}
catch (IOException io) {
ServerSettings.port += 505;
}
}
You could wrap it in a function, and instead of foundPort = true;, you would return the socket object.

how to tell whether a connection is established in java?

I tried to build a socket channel between two emulators in android. I wrote the following code:
public SocketChannel connect2node(String ip, int port) {
SocketChannel client = null;
try {
client = SocketChannel.open(new InetSocketAddress(ip, port));
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
if (!client.isConnected()) {
Log.i("server connection", "error");
return null;
}
} catch (IOException e) {
String s = e.getMessage();
e.printStackTrace();
}
return client;
}
Note I have NOT started another emulator in (ip, port), means the connection will always fail. When I start debugging the above code, I found when it came to
if (!client.isConnected()) {
It then jumps to the catch block:
e.printStackTrace();
all other lines in catch block is not executed, and the client is not null when return. So how can I tell whether the connection is successfully established or not?
The isConnected() test is pointless. If the open() fails to connect it will throw an exception.

How to determine if server closed connection (RST packet received) in Java?

I'm using Socket class for my TCP connection. But my current problem is to determine exactly disconnect reason.
In both cases (if there's connection timeout or server closed connection) I receive SocketException with "Broken pipe" message. So how I can exactly determine disconnect reason?
Thanks!
I think you should get a different Exception thrown. If you are talking about a connection then you should get a SocketException from a host which sends a reset (I think that's the RST packet) and a SocketTimeoutException if your connection times out.
If you are talking about IO then again, if the server drops the connection you will get a SocketException while if the IO times out (maybe just the read) you will get a SocketTimeoutException.
Here's the test program I used. Of course I'm bleeding sockets like crazy.
try {
new Socket().connect(new InetSocketAddress(someIpThatHangs, 8000), 1000);
fail("Should have thrown");
} catch (SocketTimeoutException e) {
// we expected it to timeout
}
try {
new Socket().connect(new InetSocketAddress(someIpThatResets, 1000));
fail("Should have thrown");
} catch (SocketException e) {
// we expected it to throw an exception immediately on reset
}
// start our server
final ServerSocket serverSocket = new ServerSocket();
int serverPort = 8000;
InetSocketAddress address = new InetSocketAddress("127.0.0.1", serverPort);
serverSocket.bind(address);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Socket clientSocket = serverSocket.accept();
System.err.println("Got a connection");
Thread.sleep(1000);
clientSocket.close();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
});
thread.start();
// wait for the server to start
Thread.sleep(100);
Socket clientSocket = new Socket();
clientSocket.connect(address);
try {
// read until the server closes the connection
clientSocket.getInputStream().read();
} catch (SocketException e) {
// expected socket exception
}
clientSocket = new Socket();
clientSocket.connect(address);
clientSocket.setSoTimeout(100);
try {
// read until the socket timeout expires
clientSocket.getInputStream().read();
} catch (SocketTimeoutException e) {
// expected read timeout exception
}
serverSocket.close();
thread.interrupt();

Categories

Resources