java DataOutputStream getOutputStream() getInputStream()

半城伤御伤魂 提交于 2019-12-11 09:06:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!