gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:49:33 27 4
gpt4 key购买 nike

我正在尝试实现我自己的 beanstalkd 客户端作为学习围棋的一种方式。 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

但数据可能包含 \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
}

最佳答案

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
}

现在,用您的自定义扫描仪包装您的 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)
}

阅读bufio package's Scanner源码。

Alternatively - is there a way of reading a specific number of bytes as specified in in example response above?

首先你需要阅读“RESERVED\r\n”行。

然后你就可以使用

nr_of_bytes : = read_number_of_butes_somehow(this.reader)
buf : = make([]byte, nr_of_bytes)
this.reader.Read(buf)

LimitedReader .

但我不喜欢这种方法。

Thanks for this - reader.Read('\n') was a typo - I corrected question. I have also attached example code of where I have got so far. As you can see, I can get the number of expected bytes of the body. Could you elaborate on why you don't like the idea of reading a specific number of bytes? This seems most logical?

我想看看 Bean 的定义,尤其是读者的部分。想象一下,这个计数器不知何故是错误的。

  1. 它很简短:您需要找到后面的“\r\n”并丢弃到那一点为止的所有内容?或不?那你为什么首先需要柜台?

  2. 它比它应该的更大(或者更糟的是它巨大!)。

    2.1 阅读器中没有下一条消息:很好,阅读比预期的要短,但没问题。

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

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

这个字节计数器一般是用来验证消息的。看起来 beanstalkd 协议(protocol)就是这种情况。

使用 Scanner,解析消息,检查长度与预期数字......利润

UPD

请注意,默认的 bufio.Scanner 无法读取超过 64k 的数据,请先使用 scanner.Buffer 设置最大长度。这很糟糕,因为您不能即时更改此选项,并且某些数据可能已被扫描仪“预”读取。

UPD2

思考我的最后更新。看看net.textproto它如何像简单状态机一样实现 dotReader。您可以先读取命令并检查有效负载的“预期字节数”来做类似的事情。

关于golang - bufio 读取多行直到 (CRLF)\r\n 定界符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37530451/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com