简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM