Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java inputStream.read()读取了错误的布尔值_Java_Sockets_Io_Inputstream_Bytebuffer - Fatal编程技术网

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

Java inputStream.read()读取了错误的布尔值,java,sockets,io,inputstream,bytebuffer,Java,Sockets,Io,Inputstream,Bytebuffer,服务器代码 if(success){ out.write("true".getBytes().length); out.write("true".getBytes()); out.flush(); } else{ out.write("fals

服务器代码

                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();
                }
客户端代码

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

虽然服务器发送了结果,但客户端读错了。这里有什么问题?我怎样才能解决它。例如,服务器发送值为true,而客户端接收值为false,您需要分步执行您正在执行的操作。显然,发送布尔值的最简单方法是像这样的单个字节

out.write(success ? 1 : 0);
读到这篇文章你就可以了

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

但是,如果您需要发送字符串,我会检查您正在读取的字符串以及正确的长度,因为二进制协议可能会失败的原因有很多,例如,您之前读取/写入的内容不正确。

服务器和客户端可能使用不同的字符集

在两侧使用一个明确的(相同的)

“看错了”并没有给我们任何信息。这里有很多错误的东西是诚实的,比如使用平台默认编码,假设所有的字符串都将是256字节,对数据进行两次编码,假设一次调用到代码>读取(字节[])< /代码>将读取所有的数据。
public byte[] getBytes(String charsetName)
            throws UnsupportedEncodingException
public String(byte[] bytes,
          String charsetName)
   throws UnsupportedEncodingException