问题
one question
in the case for example of
DataOutputStream output= new DataOutputStream(clientSocket.getOutputStream()) ;
or
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
must these objects to be created each time i need an I/O operation or just invoke a read or a write on them each time i need??? ( plus some flushing after each operaration)
回答1:
You must create these objects only once, that is, after your socket has been initialized.
回答2:
Both variants are possible, but it is more useful to create them only once.
If you want some buffering (to avoid sending a new TCP packet for each write command), you may want to think about putting a BufferedInputStream between the Socket and DataIn/Output:
DataOutput output = new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
DataInput input = new DataInputStream (new BufferedInputStream (clientSocket.getInputStream()));
I'm using the interfaces DataInput/DataOutput instead of the Stream classes here, since often you'll only need the methods defined there.
来源:https://stackoverflow.com/questions/4913559/java-dataoutputstream-getoutputstream-getinputstream