【问题标题】:inputStream.read() read wrong Boolean valueinputStream.read() 读取错误的布尔值
【发布时间】:2014-01-26 15:10:03
【问题描述】:

服务器代码

                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);

虽然服务器发送结果客户端读错了。这里有什么问题?我该如何解决。例如,服务器发送值为真,但客户端将其接收为假

【问题讨论】:

  • “读错了”并没有给我们任何信息。老实说,这里有各种各样的错误,例如使用平台默认编码,假设所有字符串都小于 256 字节,对数据进行两次编码,假设一次调用 read(byte[]) 将读取所有数据等。考虑改用DataOutputStream...

标签: java sockets io inputstream bytebuffer


【解决方案1】:

您需要逐步了解您正在做的事情。显然,发送布尔值的最简单方法是像这样使用单个字节。

out.write(success ? 1 : 0);

你会读到这个

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

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

【讨论】:

    【解决方案2】:

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

    在两边都使用一个明确的(并且相同的)。

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

    public byte[] getBytes(String charsetName)
                throws UnsupportedEncodingException
    

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

    【讨论】:

      猜你喜欢
      • 2016-10-22
      • 1970-01-01
      • 2019-01-10
      • 2018-01-20
      • 2021-09-14
      • 2020-12-29
      • 1970-01-01
      • 2014-10-19
      • 2017-05-27
      相关资源
      最近更新 更多