我有一個套接字到服務器。在TimerTask的幫助下,每隔1秒查詢服務器並通過輸出/輸入流讀取響應。但是,我收到錯誤套接字已關閉。套接字從TimerTask.run()中關閉
try (
// create TCP socket for the given hostName, remote port PortNumber
Socket echoSocket = new Socket(hostName, portNumber);
// Stream writer to the socket
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
// Stream reader from the socket
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()))
) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
// Query the server.
out.println("?");
// read response from the socket
String receivedText = in.readLine(); // ** error here
} catch (IOException e) {
e.printStackTrace();
}
}
}, 1000, 1000);
這裏是服務器套接字:
while (((receivedText = in.readLine()) != null)) {
if (receivedText.equals("?")) {
out.println(getCurrentState());
}
}
// close the connection socket
connectSocket.close();
但是,如果我用,而(真)和了Thread.sleep(1000),而不是TimerTask的的,它的工作原理。