golang - bufio读取多行直到(CRLF)\ r \n分隔符

Gra*_*avy 3 io buffer go beanstalkd

我正在尝试实现我自己的beanstalkd客户端作为学习go的一种方式.https://github.com/kr/beanstalkd/blob/master/doc/protocol.txt

目前,我正在使用bufio读取由一系列数据划分的数据\n.

res, err := this.reader.ReadLine('\n')

当我发送单个命令并读取单行响应时,这很好:INSERTED %d\r\n但是当我尝试保留作业时我发现困难,因为作业体可能是多行,因此,我不能使用\n分隔符.

有没有办法读入缓冲区直到CRLF

例如,当我发送reserve命令时.我的预期回应如下:

RESERVED <id> <bytes>\r\n
<data>\r\n
Run Code Online (Sandbox Code Playgroud)

但数据可能包含\n,所以我需要阅读,直到\r\n.

或者 - 是否有一种方法可以读取<bytes>上面示例响应中指定的特定字节数?

目前,我有(错误的处理删除):

func (this *Bean) receiveLine() (string, error) {
    res, err := this.reader.ReadString('\n')
    return res, err
}

func (this *Bean) receiveBody(numBytesToRead int) ([]byte, error) {
    res, err := this.reader.ReadString('\r\n') // What to do here to read to CRLF / up to number of expected bytes?

    return res, err
}

func (this *Bean) Reserve() (*Job, error) {

    this.send("reserve\r\n")
    res, err := this.receiveLine()

    var jobId uint64
    var bodylen int
    _, err = fmt.Sscanf(res, "RESERVED %d %d\r\n", &jobId, &bodylen)

    body, err := this.receiveBody(bodylen)

    job := new(Job)
    job.Id = jobId
    job.Body = body

    return job, nil
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*aaz 11

res,err:= this.reader.Read('\n')

对我没有任何意义.你的意思是ReadBytes/ReadSlice/ReadString?

你需要bufio.Scanner.

定义你的bufio.SplitFunc(示例是bufio.ScanLines的副本,其中包含修改以查找'\ r \n').修改它以匹配您的情况.

// dropCR drops a terminal \r from the data.
func dropCR(data []byte) []byte {
    if len(data) > 0 && data[len(data)-1] == '\r' {
        return data[0 : len(data)-1]
    }
    return data
}


func ScanCRLF(data []byte, atEOF bool) (advance int, token []byte, err error) {
        if atEOF && len(data) == 0 {
            return 0, nil, nil
        }
        if i := bytes.Index(data, []byte{'\r','\n'}); i >= 0 {
            // We have a full newline-terminated line.
            return i + 2, dropCR(data[0:i]), nil
        }
        // If we're at EOF, we have a final, non-terminated line. Return it.
        if atEOF {
            return len(data), dropCR(data), nil
        }
        // Request more data.
        return 0, nil, nil
    }
Run Code Online (Sandbox Code Playgroud)

现在,用您的自定义扫描仪包装您的io.Reader.

scanner := bufio.NewScanner(this.reader)
scanner.Split(ScanCRLF)
// Set the split function for the scanning operation.
scanner.Split(split)
// Validate the input
for scanner.Scan() {
        fmt.Printf("%s\n", scanner.Text())
}

if err := scanner.Err(); err != nil {
        fmt.Printf("Invalid input: %s", err)
}
Run Code Online (Sandbox Code Playgroud)

阅读bufio包的有关Scanner 源代码.

或者 - 是否有一种方法可以读取上面示例响应中指定的特定字节数?

首先,您需要阅读"RESERVED\r \n"行的一些方法.

然后你可以使用

nr_of_bytes : = read_number_of_butes_somehow(this.reader)
buf : = make([]byte, nr_of_bytes)
this.reader.Read(buf)
Run Code Online (Sandbox Code Playgroud)

LimitedReader.

但我不喜欢这种方法.

谢谢你 - 读者阅读('\n')是一个错字 - 我纠正了问题.我还附上了我到目前为止的示例代码.如您所见,我可以获得正文的预期字节数.你能详细说明为什么你不喜欢读取特定字节数的想法吗?这似乎最符合逻辑?

我想看看Bean的定义,尤其是读者的定义.想象一下,这个计数器在某种程度上是错误的.

  1. 它的简短:您需要找到以下"\ r \n"并丢弃到目前为止的所有内容?或不?为什么你首先需要反击呢?

  2. 它应该更大(甚至更糟糕!).

    2.1阅读器中没有下一条消息:很好,读取时间比预期短但很好.

    2.2下一条消息正在等待:呸,你读了部分消息,没有简单的方法可以恢复.

    2.3它的巨大:即使消息只有1个字节,你也无法分配内存.

该字节计数器通常用于验证消息.看起来像是beanstalkd协议的情况.

使用扫描仪,解析消息,检查长度与预期数量......利润

UPD

警告,默认bufio.Scanner读取超过64k,使用scanner.Buffer设置最大长度.这很糟糕,因为您无法动态更改此选项,并且某些数据可能已被扫描仪"预先"读取.

UPD2

想想我上次的更新.看一下net.textproto它如何实现像简单状态机一样的dotReader.你可以先做读取命令,然后检查有效负载的"预期字节".