Java sockets: DataOutputStream or OutputStream?

妖精的绣舞 提交于 2019-12-03 16:53:49

问题


I'm still relatively new to sockets, and I haven't seen any information regarding this subject.

To write to a connected socket, you can either use

socket.getOutputStream().write

Or create a new DataOutputStream from the socket OutputStream and write to that.

  • What is considered "good practice", using a DataOutputStream or OutputStream? Most of the examples I find on the internet use DataOutputStream (to send Strings, such as in a two way chat).
  • Are there any advantages or disadvantages from using DataOutputStream over OutputStream?
  • Is there any difference in performance that is noticeable between these two when, for example, sending files?

回答1:


DataOutputStream makes sure the data is formatted in a platform independent way. This is the big benefit. It makes sure the party on the other side will be able to read it. There is no significant performance difference between both.

You should use OutputStream only if you transfer raw binary data.




回答2:


Use DataOutputStream if you need the extra APIs. If you don't, there is no point. But you should always wrap the socket's output stream in a BufferedOutputStream if you are doing small writes, and flush() when appropriate, i.e. before you read the socket for example.




回答3:


Just now I came to know a difference between dataoutputstream and outputstreamwriter while working with a SOAP services... I tried to pass arabic data through request XML but in the response XML I'm getting some junk characters in place of arabic data then I tried to encode (UTF-8) the request but there is no such method to encode in DataOutputStream where as you can encode the request in OutputStreamWriter before sending the request. OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); out.write(inputXML);



来源:https://stackoverflow.com/questions/6984130/java-sockets-dataoutputstream-or-outputstream

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