Уточню вопрос(перепишу код немного по-другому):
Код | Socket socket = new Socket(remoteAddress,remotePort); PrintWriter out = new PrintWriter(new BufferedWriter (new OutputStreamWriter(socket.getOutputStream())), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); ... //в отдельном методе String str; while (true) { str = in.readLine(); if (str == null) break; System.out.println(str); } ... //в отдельном методе out.close(); try{ Thread.sleep(1000); }catch(InterruptedException e){ e.printStackTrace(); } in.close(); socket.close();
|
Почему во время Thread.sleep(1000) (т.е. после out.close()) метод in.readLine() возвратит null(т.е. out каким-то образом влияет на in,а каким - это я и хочу понять)? Конечно,можно было бы закрыть только сокет,но ради чистоты кода еще стоит закрывать и потоки(streams).Вот что по этому поводу написано в tutorial от Sun:
Код | out.close(); in.close(); stdIn.close(); echoSocket.close();
|
These lines of code fall into the category of housekeeping. A well-behaved program always cleans up after itself, and this program is well-behaved. These statements close the readers and writers connected to the socket and to the standard input stream, and close the socket connection to the server. The order here is important. You should close any streams connected to a socket before you close the socket itself. |