Saorikido
Saorikido

Reputation: 2290

What time to close socket connection in Java

Client

Socket socket = new Socket("ip", 5555);
PrintStream out = new PrintStream(socket.getOutputStream());
out.println("Hello Server!");
out.close();
socket.close();

Server

ServerSocket serverSocket = new ServerSocket(5555);

while (true) {

    //keep listening
    Socket socket = serverSocket.accept();

    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

    String line = in.readLine();

    System.out.println(line);

    in.close();
    socket.close();
}

if ignore concurrency issue, is the way to close sockets connection correct?

Upvotes: 2

Views: 2398

Answers (1)

user207421
user207421

Reputation: 311050

if ignore concurrency issue, is the way to close sockets connection correct?

Yes, but you don't need to close the socket if you've already closed the output stream.

if client closed socket immediately after sent data, will it cause some exception like 'socket is close' while server tries to read data from stream?

No. 'Socket is closed' means you closed the socket and then continued to use it. As long has the client has read everything the server is going to send, the client can close the socket: the server will read all the data the client has sent, and then get end-of-stream on the next read.

Upvotes: 4

Related Questions