JAVA 上的 TCP 套接字 - 任何字节 >= 128 都被接收为 65533 [英] TCP Socket on JAVA - Any byte >= 128 is received as 65533

查看:40
本文介绍了JAVA 上的 TCP 套接字 - 任何字节 >= 128 都被接收为 65533的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Android 上实现一个服务器,我正在使用:

I am implementing a server on Android and I am using:

while (!Thread.currentThread().isInterrupted()) {
    try {
        int r;
        String response = "";
        while ((r = input.read()) > 0) {
        ...
        }
    ...
}

我有两个问题.如果客户端向我发送一个值为 0 的字节,则服务器不会收到它.

I have two issues. If the client sends me a byte of value 0, it is not received by the server.

第二个问题是,如果字节值为 128 或更多,我不断收到 65533 的值或 11111101 的二进制值.

The second issue is, if the byte value is 128 or more, I keep receiving a value of 65533 or a binary value of 11111101.

任何人都知道如何解决这些问题.我是 JAVA 网络初学者.

Anyone knows how to solve these issues. I am a beginner in networking on JAVA.

推荐答案

我遇到了同样的问题,我在 这个问题:

I was having the same issue and I've found the answer in this question:

您正在处理二进制数据,因此您应该使用原始流 - 不要将其转换为用于读取字符的 Reader.

You're dealing with binary data so you should be using the raw stream - don't turn it into a Reader, which is meant for reading characters.

您收到的是 65533,因为这是当值无法表示为真正的 Unicode 字符时用于Unicode 替换字符"的整数.您当前代码的确切行为将取决于您系统上的默认字符编码 - 这同样不是您应该依赖的.

You're receiving 65533 because that's the integer used for the "Unicode replacement character" used when a value can't be represented as a real Unicode character. The exact behaviour of your current code will depend on the default character encoding on your system - which again isn't something you should rely on.

我失败的代码就像(简化):

My failing code was like (simplified):

InputStream is = socket.getInputStream();
BufferedReader input = new BufferedReader(new InputStreamReader(is));

int data = input.read();
if(data >=0){
    System.out.println("Obtained: "+data);
}

和你一样,它正在打印:Obtained: 65533 当一个大于 127 的数字被发送到另一边时.

Like you, it was printing: Obtained: 65533 when a number greater than 127 was sent in the other side.

要解决这个问题,只需调用InputStream.read() 方法,而不是创建任何reader:

To solve this, just call the InputStream.read() method instead of creating any reader:

InputStream is = socket.getInputStream();

int data = is.read();
if(data >=0){
    System.out.println("Obtained: "+data);
}

注意:这个问题可能被标记为与之前提到的问题重复.

Note: Probably this question could be marked as duplicate to the one previously referenced.

这篇关于JAVA 上的 TCP 套接字 - 任何字节 >= 128 都被接收为 65533的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆