호스트에서 자바 연결을 허용하는지 테스트하려면 다음 클래스를 사용하고 있습니다.자바와 테스트 소켓 연결
내 질문에 무엇이 개선 될 수 있습니까? 피드백
편집
에 대한
덕분에 나는 초 선택적 매개 변수 "타임 아웃"을 추가했습니다.
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+")));
}
}
if() try {constructs : P – OscarRyz
나는 당신의 영혼을 만나고 싶지 않다. :) – mgarciaisaia