Reputation: 918
I'm trying to create a socket that connects to a server. A user can manually enter the socket's IP address and IP port.
When the address and port are valid nothing goes wrong, but when they don't, it causes my entire app to freeze.
This is the code:
public void connect() {
try {
String txHostIP = settings.getString("txHostIP", "");
int txHostport = Integer.parseInt(settings.getString("txHostPort", ""));
//Where it all goes wrong. The program just hangs here for eternity
socket = new Socket(txHostIP, txHostport);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
} catch (IOException e) {
showMessage(context, "Something went wrong");
}
}
What I want is for a message to pop up when no connection can be made but the program doesn't throw an exception if an IP port or address is incorrect.
How can I fix this? Any help is greatly appreciated!
EDIT:
I've added some System.out prints to show how the program hangs. I've also added a socket connect timeout of 5 seconds. Still the program won't even reach that block of code.
public void connect() {
try {
String txHostIP = settings.getString("txHostIP", "");
int txHostport = Integer.parseInt(settings.getString("txHostPort", ""));
System.out.println("1");
socket = new Socket(txHostIP, txHostport);
System.out.println("2");
socket.connect(socket.getLocalSocketAddress(), 5000);
System.out.println("3");
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println("4");
} catch (IOException e) {
showMessage(context, "Something went wrong");
}
}
It just prints the 1 and then hangs on forever.
Upvotes: 2
Views: 1504
Reputation: 632
If you want to let the socket abort after a certain amount of time you have to do this:
int timeout = 5000;
int port = 1234;
String address = "localhost";
InetSocketAddress inetAddress = new InetSocketAddress(address, port);
Socket socket = new Socket();
socket.connect(inetAddress, timeout);
Otherways the socket will hang before you set the soTimeout. The connect method will throw an SocketTimeoutException if the remote host is not reachable.
Upvotes: 2
Reputation: 7029
Set a connection timeout of say, 5 seconds - run a counter based on the system clock and when the time is up, if it hasn't connected - throw the exception and cancel the connection.
Upvotes: 1