【问题标题】:Android Socket ReadLine but with different terminatorAndroid Socket ReadLine 但具有不同的终止符
【发布时间】:2014-05-26 15:16:43
【问题描述】:

在客户端,我正在尝试读取,直到出现自定义终止字节。解冻是(/ffff)

现在 readline() 读取直到收到缓冲区 /r , /n 或两者,

但是如果我想要自定义终止字节怎么办?

【问题讨论】:

  • 没有标准的方法来做到这一点。我正在从事我自己实施的项目。可以通过我重写 BufferedReader 的方法来完成,也可以自己实现。
  • 你能帮忙提供一个代码示例吗?

标签: java android sockets readline


【解决方案1】:

没有重新定义行终止符的标准方法。

正如您在BufferedReader 的源代码中所见,'\r' '\n' 行终止符是硬编码的。

您可以使用BufferedReader 源,创建自己的类并替换其中的行终止符。

另一个解决方案是创建助手类,就像我在我的一个项目中所做的那样:

public class StreamSplitter {
    private InputStream st;
    private Charset charset;

    /**
     * Construct new stream splitter.
     * @param st input stream
     * @param charset input stream charset
     */
    public StreamSplitter(InputStream st, Charset charset) {
        this.st = st;
        this.charset = charset;
    }

    // ... skip

    /**
     * Read stream until the specified marker is found. 
     * @param marker marker
     * @return 
     * @throws IOException
     */
    public String readUntil(String marker) throws IOException {
        StringBuilder res = new StringBuilder();
        if (!readUntil(marker, res)) {
                return null;
        }
        return res.toString();
    }

    /**
     * Read stream until the specified marker is found.
     * @param marker marker
     * @param res output 
     * @return <code>true</code> if marker is found, <code>false</code> if end of stream is occurred
     * @throws IOException
     */
    public boolean readUntil(String marker, StringBuilder res) throws IOException {
        byte[] markerBytes = marker.getBytes(charset);

        int b;
        int n = 0;

        while ((b = st.read()) != -1) {
            byte bb = (byte)b;

            if (markerBytes[n] == bb) {
                n++;
                if (n == markerBytes.length) {
                    return true;
                }
            }
            else {
                 if (n != 0 && res != null) {
                    for (int nn = 0; nn < n; nn++)
                        res.append((char)markerBytes[nn]);
                }

                if (res != null)
                    res.append((char)bb);
                n = 0;
            }
        }
        return false;
    }

    // ... skip 

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 2016-01-11
    • 1970-01-01
    相关资源
    最近更新 更多