我正在使用bytesCount = InputStream.read(byteArray)
从客户端读取数据:
我的服务器:
InputStream IS = Connection.getInputStream();
byte[] InData = new byte[1024];
int bytesCount = IS.read(InData);
我的客户:
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) {}
如您所见,客户端发送字符串“ABC”,但服务器收到的字节数组为InData = [-84, -19, 0, 5, 119, 3, 65, 66, 67, 0, 0, 0, ...]
和bytesCount = 9
前6个字节是什么?
答案 0 :(得分:1)
它是ObjectOutputStreamHeader,请参阅writeStreamHeader()
此处:http://developer.classpath.org/doc/java/io/ObjectOutputStream-source.html
如果要将字符串序列化为UTF8,只需使用带有UTF8编码的常规OutputStreamWriter(不是ObjectOutputStream)并写入字符串:
OutputStreamWriter ows = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
osw.write("ABC");