我正在使用套接字将串行命令传递给远程设备。并且对该请求的响应被发回并打印出来。但是,我遇到的问题是第一次是即时的,但其余时间最多可能需要 20 秒才能收到回复。
我认为问题在于我尝试线程,但我不完全确定。
new Thread() {
@Override
public void run() {
System.out.println("opened");
try {
isSocketRetrieving.setText("Opening Socket");
socket = new Socket(getAddress(), getRemotePort()));
DataOutput = new DataOutputStream(socket
.getOutputStream());
inFromServer = new BufferedReader(
new InputStreamReader(socket
.getInputStream()));
String line = "";
isSocketRetrieving.setText("Reading Stream......");
while ((line = inFromServer.readLine()) != null) {
System.out.println(line);
if (line.contains(getHandshakeRequest())) {
DataOutput.write((getHandshakeResponse()toString() + "\r").getBytes());
DataOutput.flush();
DataOutput
.write((getCommand().toString() + "\r").getBytes());
DataOutput.flush();
int pause = (line.length()*8*1000)/getBaud();
sleep(pause);
} else if (line.contains(readingObject
.getExpected())) {
System.out.println(line);
textArea.append("value = " + line
+ "\n");
textAreaScroll.revalidate();
System.out.println("Got Value");
break;
}
}
System.out.println("Ended");
try {
inFromServer.close();
DataOutput.close();
socket.close();
isSocketRetrieving.setText("Socket is inactive...");
rs232Table.addMouseListener(listener);
interrupt();
join();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Thread exited");
}
} catch (NumberFormatException e1) {
e1.printStackTrace();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();