What happens after I close the IO stream in the Java socket? (for example, to turn off the output stream)

Source: Internet
Author: User

Disclaimer: This post is illustrated with the example of closing the output stream in the socket.

To facilitate the explanation, we put dataoutputstream dout = new DataOutputStream (New Bufferedoutputstream (Mysocket.getoutputstream ())); The dout in the socket output stream as the endorsement. Similarly, DIN is the endorsement of the input stream.

Actions that can cause dout to be closed are:

1, call Dout.close (), or din.close (), because using this flow to close will cause the socket to be closed , so the input and output stream will not be reused.

2, call Socket.close ();

3, call Socket.shutdownoutputstream (); Unilaterally close the dout, at which time the din can also be used normally.

Below, I will perform 3 tests on the closed output stream in the socket

output stream off test one: Does the socket close? Output stream shutdown Test two: Can the stream be reopened? Output stream shutdown Test Three: is the data in the output buffer discarded or sent?The test results are as follows:

Test one: Dout.close (), will cause the socket to be closed, but Socket.shutdownoutputstream () will not.

Test two: No, the exception will be thrown!

Test three: Discard

Client program:

 PackageCom.test2;ImportJava.io.*;Importjava.net.*;/*** @ClassName: sockettest* @Description: In the test socket, is the socket closed after the stream is closed? Is it possible to re-open the stream? Output buffer data is sent out, or discarded? * @authorJogging School android* @date 2011-11-12 Morning 11:15:21**/ Public classsockettest {Socket mysocket;    DataOutputStream dout;  Public Static voidMain (string[] args) {Newsockettest (); }         Publicsockettest () {//test of output stream shutdown: Socket closed? test1 (); //output stream shutdown Test two: Can the stream be reopened? test2 (); //output stream shutdown test Three: is the data in the output buffer discarded or sent? test3 (); }    Private voidtest1 () {//test of output stream shutdown: Socket closed? System.out.println ("\n****2 way to turn off the output stream, is the socket closed?") \ n "); Try{mysocket=NewSocket ("27.154.122.233", 9999); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }                Try{dout=NewDataOutputStream (NewBufferedoutputstream (Mysocket.getoutputstream ())); //The following sentence is mainly used to prove that the socket is actually open .SYSTEM.OUT.PRINTLN ("The output stream just opened, is the socket closed?") " +mysocket.isclosed ());            Mysocket.shutdownoutput (); System.out.println ("Using Shutdownoutput to close the output stream, is the socket closed?" " +mysocket.isclosed ());            Dout.close (); System.out.println ("Close the output stream with close, does the socket close?" " +mysocket.isclosed ()); } Catch(IOException e) {e.printstacktrace (); }    }    Private voidtest2 () {//output stream shutdown Test Two: can the output stream be re-opened after using Shutdownoutputstream? System.out.println ("\n**** the output stream can be re-opened after using Shutdownoutputstream?") \ n "); Try{mysocket=NewSocket ("27.154.122.233", 9999); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }                Try{dout=NewDataOutputStream (NewBufferedoutputstream (Mysocket.getoutputstream ()));            Mysocket.shutdownoutput (); //re-opening the output streamDout =NewDataOutputStream (Mysocket.getoutputstream ()); Dout.writeutf ("Will I be allowed to re-open?" "); //clear the output cache to ensure that messages can reach the server when the Dout channel is not a problemDout.flush (); } Catch(IOException e) {e.printstacktrace (); } finally {            Try{mysocket.close (); } Catch(IOException e) {e.printstacktrace (); }        }    }        Private voidtest3 () {//output stream shutdown test Three: is the data in the output buffer discarded or sent? System.out.println ("is the data in the \n*** output buffer discarded or sent?") \ n "); Try{mysocket=NewSocket ("27.154.122.233", 9999); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }                Try{dout=NewDataOutputStream (NewBufferedoutputstream (Mysocket.getoutputstream ())); Dout.writeutf ("After the Shutdownoutput, can the data be sent out?" ");        Mysocket.shutdownoutput (); } Catch(IOException e) {e.printstacktrace (); }    }}

Server-side programs:

/*** @Title: serversockettest.java* @Package com.test1* @Description: TODO (The file is "in the socket, the stream is off, what happens after" the Sever Test side) *@authorJogging School android* @date 2011-11-12 Morning 11:31:05*@versionV1.0*/ PackageCom.test1;ImportJava.io.*;Importjava.net.*; Public classServersockettestextendsthread{PrivateServerSocket myServerSocket; Private Final intPORT = 9999;  Public Static voidMain (string[] args) {serversockettest SST=Newserversockettest ();    Sst.start (); }         Publicserversockettest () {//Initialize a servesocket end        Try{myServerSocket=NewServerSocket (PORT); } Catch(IOException e) {e.printstacktrace (); }    }         Public voidrun () { while(true) {System.out.println ("I am the server, I am listening on port 9999 ...."); Try{Socket Socket=myserversocket.accept (); DataInputStream din=NewDataInputStream (NewBufferedinputstream (Socket.getinputstream ())); String Msgin=Din.readutf ();            System.out.println (Msgin.trim ()); } Catch(IOException e) {e.printstacktrace (); }        }    }}

Note one point:

In Test3 (), because dout = new DataOutputStream (Newbufferedoutputstream (Mysocket.getoutputstream ())), buffered is used, So after the Dout.writeutf () method, if Dout.flush () is not used, the data will be present in the output cache and will not be sent out.

If our team Dout's statement is, dout = new DataOutputStream (Mysocket.getoutputstream ()), then the data will be sent out immediately. (unless the other party does not call read () to read the data, and the amount of data is enormous, exceeding the other's input cache.) However, at this time Dout.writeutf (); it will jam here. )


The following is the output of the client and server console after the program is run:

---------------------------------- Client --------------------------

Java.net.SocketException:Socket output is shutdown
At Java.net.Socket.getOutputStream (Unknown Source)
At Com.test2.SocketTest.test2 (sockettest.java:66)
At Com.test2.sockettest.<init> (sockettest.java:22)
At Com.test2.SocketTest.main (sockettest.java:15)

2 ways to turn off the output stream, is the socket closed? ***

The output stream just opened, is the socket closed? False
Using Shutdownoutput to close the output stream, is the socket closed? False
Close the output stream using close, does the socket close? True

Can the output stream be re-opened after using Shutdownoutputstream? ***


Is the data in the output buffer discarded or sent? ****

---------------------------------Server------------------------------

I am the server, I am listening on the 9999 port ....
I am the server, I am listening on the 9999 port ....
Java.io.EOFException
At Java.io.DataInputStream.readUnsignedShort (Unknown Source)
At Java.io.DataInputStream.readUTF (Unknown Source)
At Java.io.DataInputStream.readUTF (Unknown Source)
At Com.test1.ServerSocketTest.run (serversockettest.java:37)
Java.io.EOFException
At Java.io.DataInputStream.readUnsignedShort (Unknown Source)
At Java.io.DataInputStream.readUTF (Unknown Source)
At Java.io.DataInputStream.readUTF (Unknown Source)
At Com.test1.ServerSocketTest.run (serversockettest.java:37)
Java.io.EOFException
At Java.io.DataInputStream.readUnsignedShort (Unknown Source)

I am the server, I am listening on the 9999 port ....

At Java.io.DataInputStream.readUTF (Unknown Source)
At Java.io.DataInputStream.readUTF (Unknown Source)
At Com.test1.ServerSocketTest.run (serversockettest.java:37)

Reference:

What happens after I close the IO stream in the Java socket? (for example, to turn off the output stream)

What happens after I close the IO stream in the Java socket? (for example, to turn off the output stream)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.