What is wrong with this simple Java TCP server/client example?
First, start the server:
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Throwable {
ServerSocket ss = new ServerSocket(2345);
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
Thread.sleep(5000);
for (int i = 0; i < 3; i++) {
os.write("A".getBytes());
os.flush();
System.out.println("Written in cycle " + i);
}
os.close();
s.close();
}
}
Start the client and watch the server after that:
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Throwable{
Socket s=new Socket("localhost",2345);
s.close();
System.out.println("Closed");
}
}
The client socket is closed immediately. However, the socket write operation on the server fails in the second loop, i.e. the first write does not throw an exception.
This is the server's execution output:
Written in cycle 0
Exception in thread "main" java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:124)
at Server.main(Server.java:16)