我想寫一個類,將掃描本地網絡的服務將運行。Java網絡服務掃描器
問題是,如果地址沒有激活(無回覆),它會在其上掛起5秒以上,這是不好的。
我想在幾秒鐘內完成此掃描。任何人都可以提供建議嗎?
我的代碼部分低於
int port = 1338;
PrintWriter out = null;
BufferedReader in = null;
for (int i = 1; i < 254; i++){
try {
System.out.println(iIPv4+i);
Socket kkSocket = null;
kkSocket = new Socket(iIPv4+i, port);
kkSocket.setKeepAlive(false);
kkSocket.setSoTimeout(5);
kkSocket.setTcpNoDelay(false);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
out.println("Scanning!");
String fromServer;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Server here!"))
break;
}
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
感謝您的答案!這是我的代碼給其他人尋找這個!
for (int i = 1; i < 254; i++){
try {
System.out.println(iIPv4+i);
Socket mySocket = new Socket();
SocketAddress address = new InetSocketAddress(iIPv4+i, port);
mySocket.connect(address, 5);
out = new PrintWriter(mySocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
out.println("Scanning!");
String fromServer;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Server here!"))
break;
}
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
感謝您的建議,我會嘗試一下! – David 2011-02-10 15:02:44
它的工作原理!謝謝! – David 2011-02-10 15:12:06