I'm trying to write a class that will scan the local network for a service that will be running.
The problem is that if the address is not active (no reply) it hangs up on it for 5+ seconds which isn't good.
I want to have this scan done in a few seconds. Can anyone offer some advice?
My code part is below
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) {
}
}
Thank you for the answers! Here's my code for anyone else looking for this!
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) {
}
}
You could try connecting to the server explicitly by invoking
Socket.connect( address, timeout )
.