我有一个程序,它从实现(布尔类型)的类中分配一个布尔值。但是当我运行程序时,它会在我从类中分配布尔值后卡住。
这是我的代码:
班级:
public static class TCP_Ping implements Callable<Boolean> {
private final BufferedReader in;
private final PrintWriter out;
private final String ip;
private final int port;
private final int time;
public TCP_Ping(BufferedReader _in, PrintWriter _out, String _ip,
int _port, int _time) {
this.in = _in;
this.out = _out;
this.ip = _ip;
this.port = _port;
this.time = _time;
}
@Override
public Boolean call() {
boolean returnValue = false;
String address = ip + ":" + port;
long before = System.nanoTime();
out.println(new byte[64]);
System.out.println("(" + time + ") Sent 64 bytes of data to "
+ address + "...");
try {
if ((in.readLine()) != null) {
int size = in.readLine().toString().getBytes().length;
long after = System.nanoTime();
long s = ((after - before) / 1000000L) / 1000;
System.out.println("(" + time + ") Recieved reply from "
+ address + " (" + size + " bytes), time = " + s
+ " seconds...");
returnValue = true;
} else if ((in.readLine()) == null) {
long after = System.nanoTime();
long s = ((after - before) / 1000000L) / 1000;
System.out.println("(" + time
+ ") Failed to recieve reply from " + address
+ ", time = " + s + " seconds...");
returnValue = false;
}
} catch (IOException exc) {
long after = System.nanoTime();
long s = ((after - before) / 1000000L) / 1000;
System.err.println("(" + time
+ ") Failed to recieve reply from " + address
+ ", time = " + s + " seconds...");
returnValue = false;
}
return returnValue;
}
}
分配布尔值的地方:
System.out.println("Starting ping...");
System.out.println("Will ping " + address
+ " with 64 bytes of data...");
long start = System.currentTimeMillis();
final FutureTask<Boolean> ft1 = new FutureTask<Boolean>(
new TCP_Ping(in, out, ip, port, 1));
Thread t1 = new Thread(ft1);
t1.start();
try {
while (t1.isAlive()) {
t1.join(20000);
if (((System.currentTimeMillis() - start) >= 20000)
&& t1.isAlive()) {
t1.interrupt();
System.out
.println("(1) - Failed to receive reply from "
+ address
+ ", since the ping timed out, time = 20 seconds...");
result = false;
break;
}
break;
}
} catch (InterruptedException exc) {
System.err
.println("(1) - An interuption occurred during a ping to "
+ address + "...");
}
try {
result = ft1.get();
} catch (Exception exc) {
System.err.println("Uh, oh! An internal error occurred!");
}
答案 0 :(得分:1)
你的问题不清楚,但我怀疑这是问题所在:
if ((in.readLine()) != null) {
int size = in.readLine().toString().getBytes().length;
从输入中读取两个行。你几乎肯定不是那个意思。我怀疑你想要的东西:
String line = in.readLine();
if (line != null) {
int size = line.getBytes().length;
...虽然我强烈建议不使用String.getBytes
而不指定编码。
同样,您正在阅读另一个行:
} else if ((in.readLine()) == null) {
...虽然如果你已经阅读了最后一行,你只会进入else
状态,但目前还不清楚为什么你在这里有条件。我认为你只是指一个简单的else
条款。