dboss 读取byte导致 乱码问题

最近偶发情况虾遇到字符乱码问题如下:

 
最开始以为是jython的bug,后来定位发现是dboss readLine的实现上, 应该是byte处理的问题,之前的实现是:

    public String readLine(int length) throws IOException {
        String buf = "";
        int index = 0;
        while (true) {
            index = buf.indexOf("\r\n");
            if (index >= 0) {
                break;
            }
            int bytesToRead = Math.min(input.available(), length);
            if (bytesToRead > 0) {
                byte[] data = new byte[bytesToRead];
                input.read(data);
                String line = new String(data, DbossClientConstant.ENCODE);
                buf += line;
            } else {
                int b = input.read(); // 此操作会阻塞,直到有数据被读到
                if (b < 0) {
                    throw new IOException(
                                          " end of the socket input stream has been reached,may be server socket is closed!");
                } else {
                    input.unread(b);
                    continue;
                }
            }
        }
        return buf.substring(0, index);

    }

 这个存在一个问题,每次从缓存区读取byte都转换成string,有可能存在读取到一一半的byte,导致乱码。修改之后的代码:

  public String readLine(int length) throws IOException {
        int bytesToRead = Math.min(input.available(), length);
        ByteArrayOutputStream output = new ByteArrayOutputStream(bytesToRead);
        int index = 0;
        byte[] buffer = null;
        while (true) {
            buffer = output.toByteArray();
            index = ToolUtil.indexOf(buffer, EOF);
            if (index >= 0) {
                break;
            }
            bytesToRead = Math.min(input.available(), length);
            if (bytesToRead > 0) {
                byte[] bytes = new byte[bytesToRead];
                input.read(bytes);
                output.write(bytes);
            } else {
                int b = input.read(); // 此操作会阻塞,直到有数据被读到
                if (b < 0) {
                    throw new IOException(
                                          " end of the socket input stream has been reached,may be server socket is closed!");
                } else {
                    input.unread(b);
                    continue;
                }
            }
        }
        return new String(buffer, DbossClientConstant.ENCODE);

    }

 

ps:还有后续问题: 记录一次bug解决过程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值