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前端其它相关文章!