我正在尝试检查是否有几个pors是打开的,如果80端口是打开的 - 发送http请求然后在控制台中显示结果。每个端口都在他自己的线程中检查。
我发送这样的请求
public static void send(Socket sock, String host) throws IOException{
PrintWriter pw = new PrintWriter(sock.getOutputStream());
pw.println("GET / HTTP/1.1");
pw.println("Host: " + host);
pw.println("");
pw.flush();
}
在类TCPClient
中,我使用它并将结果作为字节返回,然后将其显示为控制台。
try {
sock = new Socket(host, port);
System.out.println("port " + port + " is in use");
// send request
HttpSender.send(sock, host);
BufferedReader bf = new BufferedReader(new InputStreamReader(sock.getInputStream()));
StringBuffer response = new StringBuffer();
String line = "";
while((line = bf.readLine()) != null) {
response.append(line);
response.append('\r');
}
bf.close();
return String.valueOf(response).getBytes(); // in method run I show it
} catch (SocketException e) {
return ("port " + port + " is free").getBytes();
}
我为端口检查创建了线程池。
public class ThreadPool {
private static int MAX_THREADS = 5;
private static String DESTINATION = "http://stackoverflow.com/";
private ExecutorService es = null;
public ThreadPool() {
es = Executors.newFixedThreadPool(MAX_THREADS);
}
public void perform(int start, int end) throws UnknownHostException {
for (int i = start; i <= end; i++) {
Runnable req = new TCPClient(DESTINATION, i);
es.execute(req);
}
es.shutdown();
while (!es.isTerminated()) {
}
;
System.out.println("all ports checked!");
}
}
当我将目的地设置为www.stackoverflow.com
并获得包含it was moved permanently to http://stackoverflow.com/
的文字的文档时。当我设置此目的地时 - 我已经UnknownhostException
。
问题出在哪里?
答案 0 :(得分:2)
你试过private static String DESTINATION = "stackoverflow.com";
吗?字符串"http://stackoverflow.com"
不是主机名,而是URL。