[英]InputStream.read(byte[] b) returns unexpected bytes
I'm using bytesCount = InputStream.read(byteArray)
to read data from a client: 我正在使用bytesCount = InputStream.read(byteArray)
从客户端读取数据:
My Server: 我的服务器:
InputStream IS = Connection.getInputStream();
byte[] InData = new byte[1024];
int bytesCount = IS.read(InData);
My Client: 我的客户:
ObjectOutputStream OOS = null;
try {
OOS = new ObjectOutputStream(connection.getOutputStream());
} catch (Exception e) {}
OutputStreamWriter OSW = new OutputStreamWriter(OOS);
try {
OSW.write("ABC");
OSW.flush();
} catch (Exception e) {}
As you can see, the client sends a string "ABC", but the byte array that the server receives is InData = [-84, -19, 0, 5, 119, 3, 65, 66, 67, 0, 0, 0, ...]
and bytesCount = 9
如您所见,客户端发送了一个字符串“ ABC”,但是服务器接收的字节数组是InData = [-84, -19, 0, 5, 119, 3, 65, 66, 67, 0, 0, 0, ...]
和bytesCount = 9
What are those first 6 bytes? 前6个字节是什么?
It's the ObjectOutputStreamHeader, see writeStreamHeader()
here: http://developer.classpath.org/doc/java/io/ObjectOutputStream-source.html 它是ObjectOutputStreamHeader,请在此处查看writeStreamHeader()
: http : //developer.classpath.org/doc/java/io/ObjectOutputStream-source.html
If you want to serialize the string as UTF8, just use a regular OutputStreamWriter (not an ObjectOutputStream) with UTF8 encoding and write the string: 如果要将字符串序列化为UTF8,只需使用具有UTF8编码的常规OutputStreamWriter(而不是ObjectOutputStream)并写入字符串:
OutputStreamWriter ows = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
osw.write("ABC");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.