简体   繁体   English

inputStream.read()读取错误的布尔值

[英]inputStream.read() read wrong Boolean value

Sever code 服务器代码

                if(success){
                    out.write("true".getBytes().length);
                    out.write("true".getBytes());
                    out.flush();
                }
                else{
                    out.write("false".getBytes().length);
                    out.write("false".getBytes());
                    out.flush();
                }

Client Code 客户代码

        int size = inputStream.read();
        byte[] buf = new byte[size];
        inputStream.read(buf);
        ns = new String(buf);
        Boolean.valueOf(ns);

Although the sever send the result client read it wrong. 尽管服务器发送结果,但客户端却读错了。 What is the problem in here? 这里有什么问题? how can i solve it. 我该怎么解决。 As example sever send value true but client receive it as false 例如,服务器发送值为true,但客户端将其接收为false

You need to step thread what you are doing exactly. 您需要逐步执行正在执行的操作。 Obviously the simplest way to sent a boolean is as a single byte like this. 显然,发送布尔值的最简单方法是像这样的单个字节。

out.write(success ? 1 : 0);

and to read this you would do 并阅读此书,你会做

boolean success = in.read() != 0;

However, if you need to send a string, I would check what string you are reading and what the correct length is, because there is any number of reasons a binary protocol can fail, eg because the previous thing you read/wrote was incorrect. 但是,如果您需要发送一个字符串,我会检查您正在读取的字符串以及正确的长度,这是因为二进制协议失败的原因有很多,例如,由于您先前读/写的内容不正确。

Server and Client are probably using different charsets. 服务器和客户端可能使用不同的字符集。

Use an explicit one (and the same) in both sides. 在两侧使用显式(相同)。

see http://docs.oracle.com/javase/6/docs/api/java/lang/String.html 参见http://docs.oracle.com/javase/6/docs/api/java/lang/String.html

public byte[] getBytes(String charsetName)
            throws UnsupportedEncodingException

and

public String(byte[] bytes,
          String charsetName)
   throws UnsupportedEncodingException

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

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