Correct closing posture of Socket

The java socket corresponds to the tcp in the network protocol. The tcp three-way handshake, four waved hands, and the status in 11 are not mentioned here. I don’t know if you don’t pay attention when you use the socket. Report errors to various exceptions.
E.g:

java.net.SocketException:socket is closed
错误提示的出现场景:
自己主动关闭了socket,但是之后还从里面读写数据


Software caused connection abort: socket write error
错误提示的出现场景:
对方已经关闭socket,依旧向对方写数据


connection reset (by peer)
错误提示出现的场景:
一端socket被关闭,另一端仍然发送数据,发送的第一个数据包 connection reset by peer
一端socket退出,退出时为关闭连接,另一端读数据 connection reset

Therefore, when using a socket, you need to agree on the conditions for both parties to complete the reading and writing, and then close the input and output streams:

socket.shutdownInput();
socket.shutdownOutput();

That is, when one party finishes writing, call shutdownOutput to close the output stream, then the other party's read method will return -1, then the other party knows that you have finished writing, the other party can close the input stream, and then wait for the other party to finish writing after calling shutdownOutput When you call shutdownInput again, both parties normally close the input and output streams, and the socket will not be abnormal at this time.
The following is an example of socket interaction:
Server side

public class OioServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("socket = " + socket);
            new Thread(() -> {
                try {
                    InputStream in = socket.getInputStream();
                    OutputStream out = socket.getOutputStream();
                    out.write("hello! I get your message that is follow".getBytes(Charset.forName("UTF-8")));
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = in.read(buf)) != -1) {
                        System.out.print(new String(buf, 0, len, Charset.forName("UTF-8")));
                        out.write(buf, 0, len);
                    }
                    out.write("\n end \n".getBytes(Charset.forName("UTF-8")));
                    out.flush();
                    socket.shutdownInput();
                    socket.shutdownOutput();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}

Client side

public class OioClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 8080);
        InputStream in = socket.getInputStream();
        new Thread(() -> {
            BufferedInputStream bufferIn = new BufferedInputStream(in);
            byte[] buf = new byte[1024];
            try {
                int len;
                while ((len = bufferIn.read(buf)) != -1) {
                    System.out.print(new String(buf, 0, len, Charset.forName("UTF-8")));
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
            try {
                socket.shutdownInput();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }).start();
        OutputStream out = socket.getOutputStream();
        int cout = 10;
        while (cout-- > 0) {
            out.write(("this time is " + System.currentTimeMillis() + "\n").getBytes("UTF-8"));
        }
        socket.shutdownOutput();
    }
}


 

Guess you like

Origin blog.csdn.net/bj_chengrong/article/details/103815517