我使用以下类来测试主机是否接受来自java的连接与Java的测试套接字连接
我的问题是,这里可以增强什么?
感谢您的反馈
编辑
我已经加入以秒可选参数 “超时”。
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 2009-08-13 18:42:01
我不想见到你的灵魂伴侣,然后:) – mgarciaisaia 2014-02-18 20:33:31