Używam poniższej klasy do sprawdzenia, czy host akceptuje połączenie z javapołączenie gniazda testowego z językiem Java
Moje pytanie brzmi, co można poprawić tutaj?
Dzięki za opinie
EDIT
Dodałem opcjonalny parametr "timeout" w kilka sekund.
import java.io.IOException;
import java.net.Socket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
public class TestConnection {
public static void main(String [] args) {
int timeout = 2000; // two seconds
if(isInvalidInput(args)) {
System.err.println("Usage: java TestConnection remotehost port [timeout_seconds]");
System.exit(-1);
} else if (args.length == 3) try {
timeout = Integer.parseInt(args[2]) * 1000;
} catch(NumberFormatException nfe){}
String host = args[0];
String port = args[1];
System.out.printf("Attempting: %s port: %s ....\n", host, port);
Socket socket = new Socket();
InetSocketAddress endPoint = new InetSocketAddress(host,
Integer.parseInt(port) );
if (endPoint.isUnresolved()) {
System.out.println("Failure " + endPoint);
} else try {
socket.connect( endPoint , timeout);
System.out.printf("Success: %s \n", endPoint);
} catch(IOException ioe) {
System.out.printf("Failure: %s message: %s - %s \n",
endPoint , ioe.getClass().getSimpleName(), ioe.getMessage());
} finally {
if (socket != null) try {
socket.close();
} catch(IOException ioe) {}
}
}
/**
* Validates the number of arguments is exactly 2 and the second is a number.
* @return true is args.length == 2 && args[1].matches(\\d+);
*/
private static final boolean isInvalidInput(String [] args) {
return (args.length < 2
|| (args.length >= 2 && !args[1].matches("\\d+")));
}
}
Uwielbiam if() try {konstruuje: P – OscarRyz
Nie chcę spotkać twojej bratniej duszy, wtedy :) – mgarciaisaia