No exception is thrown when socket is closed

When the server socket is closed the client doesn't receive any exception even after **writing** on the **OutputStream** and the server socket is already **close**. Giving the following classes to test that: public class ModemServerSocket { public static void main(String[] args) throws IOException, InterruptedException { ServerSocket serverSocket = new ServerSocket(63333); Socket client = serverSocket.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8")); String s; while ((s = reader.readLine()) != null) { System.out.println(s); if (s.equals("q")) { break; } } serverSocket.close(); } } public class ModemClientSocket { public static void main(String[] args) throws IOException, InterruptedException { Socket socket = new Socket("localhost", 63333); PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"), true); String[] sArray = {"hello", "q", "still there?"}; for (String s : sArray) { writer.println(s); if (s.equals("q")) { Thread.sleep(5 * 1000); } } System.out.println("Whoop. No exception. The client didn't notice."); } } What I did was to launch the ModemServerSocket application then after that I launched the ModemClientSocket application. **ModemServerSocket Output**: hello q **ModemClientSocket Output**: Whoop. No exception. The client didn't notice. Is this the expected behavior? Why is happening this? However I did another test where I close the ModemClientSocket and the ModemServerSocket tries to read from the InputStream in that case I got an **java.net.SocketException** which is what I expected. The weird thing is that is not happening for the **PrintWriter** (OutputStream) and no exception is thrown. I used **Java 1.6.0 Update 26** for the tests.

以上就是No exception is thrown when socket is closed的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏