《Java—Socket二进制通讯读取一行》

2023年2月10日08:58:54

Socket二进制通讯,结束标志用换行。这样可以分次接收数据。提供二进制数据读取一行方法。

public static byte[] readLine(InputStream in) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    int c = -1;
    while ((c = in.read()) != -1) {
        if (c == '\n') {
            in.mark(1);
            if (in.read() != '\r') {
                in.reset();
            }
            break;
        }

        if (c == '\r') {
            in.mark(1);
            if (in.read() != '\n') {
                in.reset();
            }
            break;
        }
        bos.write(c);
    }

    return bos.toByteArray();
}

  • 作者:IT痴者
  • 原文链接:https://wxfjava.blog.csdn.net/article/details/52242179
    更新时间:2023年2月10日08:58:54 ,共 352 字。