我正在尝试编写一个类来扫描本地网络以查找将要运行的服务。
问题是,如果地址不活跃(没有回复),它会挂断 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) {
}
}