简体   繁体   English

用TCP发送负字节

[英]sending negative bytes with tcp

I am sending a byte by a TCP connection, when I send a single negative number (like -30 in this example) I get three bytes: 我通过TCP连接发送一个字节,当我发送一个负数(例如本例中的-30 )时,我得到三个字节:

Client Side: 客户端:

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
out.write((byte)-30);
out.flush();
out.close();

Server Side: 服务器端:

is = new DataInputStream(clientSocket.getInputStream());
is.readFully(bbb);
for (int i=0;i<bbb.length;i++)
    System.out.println(i+":"+bbb[i]);

what i get is: 我得到的是:

0:-17
1:-65
2:-94

but I sent just -30 但我只寄了-30

You're using a writer, and you're calling Writer.write(int) : 您正在使用Writer.write(int) ,并且正在调用Writer.write(int)

Writes a single character. 写一个字符。 The character to be written is contained in the 16 low-order bits of the given integer value; 给定整数值的16个低位包含在要写入的字符中。 the 16 high-order bits are ignored. 16个高位被忽略。

So you've got an conversion to int , then the bottom 16 bits of that int are taken. 因此,您已经转换为int ,然后采用该int 16位。 So you're actually writing Unicode character 65506 ( U+FFE2 ), in your platform default encoding (which appears to be UTF-8). 因此,您实际上是以平台默认编码(似乎为UTF-8)编写Unicode字符65506( U + FFE2 )。 That's not what you want to write, but that's what you are writing. 这不是你想要写什么,但是这是你写什么。

If you only want to write binary data, you shouldn't be using a Writer at all. 如果只想写入二进制数据,则根本不应该使用Writer Just use OutputStream - wrap it in DataOutputStream if you want, but don't use a Writer . 只需使用OutputStream如果需要,可以将其包装在DataOutputStream ,但不要使用Writer The Writer classes are for text. Writer类用于文本。

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

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