我正在尝试编写一个类,该类将扫描本地网络以查找将要运行的服务。
问题是,如果地址未激活(没有回复),它会挂起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) {
}
}
答案 0 :(得分:4)
您可以尝试通过调用Socket.connect( address, timeout )
显式连接到服务器。
Socket kkSocket = new Socket();
kkSocket.bind( null )/ // bind socket to random local address, but you might not need to do this
kkSocket.connect( new InetSocketAddress(iIPv4+i, port), 500 ); //timeout is in milliseconds
答案 1 :(得分:3)
您可以使用noarg构造函数Socket()
创建一个未连接的套接字,然后使用较小的超时值调用connect(SocketAddress endpoint, int timeout)
。
Socket socket = new Socket();
InetSocketAddress endpoint = new InetSocketAddress("localhost", 80);
int timeout = 1;
socket.connect(endpoint, timeout);