简体   繁体   English

Java套接字写入byte []而不是String

[英]Java socket write byte[] instead of String

I'm new to socket programming, and I've been following several tutorials like this one http://www.myandroidsolutions.com/2012/07/20/android-tcp-connection-tutorial/ and was able to build a client-server architecture over TCP using socket. 我是套接字编程的新手,而且我一直在关注这样的几本教程http://www.myandroidsolutions.com/2012/07/20/android-tcp-connection-tutorial/并能够构建客户端使用套接字的TCP服务器结构。

The thing is, the tutorials are basic so they teaches you how to send using PrintWriter and BufferedReader which seems to write and read String . 事实是,这些教程是基础知识,因此它们教您如何使用似乎写和读String PrintWriterBufferedReader进行发送。 I have to encrypt my data and send it as byte[] , so the question will be: 我必须加密我的数据并将其作为byte[]发送,所以问题将是:

  1. For this mean, can I still use PrintWriter and BufferedReader ? 为此,我仍然可以使用PrintWriterBufferedReader吗? if not then 如果没有
  2. What classes should I use for this means and how?, I have seen DataOutputStream and DataInputStream and several others, but have not found their difference or why use one or another. 我应该使用哪些类以及如何使用这些类?,我已经看到了DataOutputStreamDataInputStream以及其他几个类,但是没有发现它们的区别或为什么使用一个或另一个。

PS: The encryption part is already done, so don't worry about it as it is not the question :) PS:加密部分已经完成,所以不用担心,因为这不是问题:)

You should use an OutputStream to write and an InputStream to read. 您应该使用OutputStream进行写入,并使用InputStream进行读取。 Those are for binary data - anything with a suffix of Writer or Reader is for text data. 这些用于二进制数据-带有WriterReader后缀的任何内容都用于文本数据。

You may find DataOutputStream and DataInputStream useful - they basically add some services wrapped around a vanilla OutputStream . 可能会发现DataOutputStreamDataInputStream有用-它们基本上会添加一些包装在原始OutputStream周围的服务。 But if all you need to do is write a byte[] to a stream, then plain OutputStream is fine. 但是,如果您只需要向流中写入一个byte[] ,那么普通的OutputStream就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM