如何读取一对值?

huangapple go评论86阅读模式
英文:

How do I read up to a pair of values?

问题

所以我有一个从TCP连接中读取值的函数。我想要读取到分隔符'\r'为止的行。到目前为止,我有以下代码:

func func1(someconnection net.Conn) string {
    c := bufio.NewReader(someconnection)
    buff1 := make([]byte, predefinedsizeofmessage)
    buff1, err := c.ReadBytes(byte('\r'))

    if err != nil {
        fmt.Printf("Connection closed")
    }

    message := strings.Trim(string(buff1), delimiter)

    if len(message) == predefinedsizeofmessage {
        fmt.Printf("The message is in the wrong format")
    }

    fmt.Printf("The message is: %s\n", message)

    return message
}

显然,这种方法在读取到分隔符之前读取到'\r'时会出现问题。我看到了使用Scanner的示例,我尝试过,但由于某种原因,当使用Scanner时,客户端会调用超时。也许是我没有正确实现Scanner。

英文:

So I have a function that reads values from a TCP connection. I want to read the line until a delimiter '\b\r'. So far I have

func func1(someconnection net.Conn) string {
	c := bufio.NewReader(someconnection)
	buff1 := make([]byte, predefinedsizeofmessage)
	buff1, err := c.ReadBytes(byte('\r'))

	if err != nil {
		fmt.Printf("Connection closed")
	}

	message:= strings.Trim(string(buff1), delimiter)

	if len(message) == predefinedsizeofmessage {
		fmt.Printf("The message is in the wrong format")
	}

	fmt.Printf("The messageis: %s\n", message)

	return message
}

This is clearly problematic in case I read a \r before the delimiter. I've seen examples of the use of Scanners which I've tried but for some reason, the client calls a timeout when they are used. Perhaps, I implemented the Scanner improperly.

答案1

得分: 1

bufio.Reader只支持单字节的分隔符,你应该使用bufio.Scanner和自定义的分割函数来分割多字节的分隔符。

也许可以修改 https://stackoverflow.com/a/37531472/1205448 的版本。

英文:

The bufio.Reader only supports single byte delimiters, you should use a bufio.Scanner with a custom split function to split on multi-byte delimiters.

Perhaps a modified version of https://stackoverflow.com/a/37531472/1205448

huangapple
  • 本文由 发表于 2022年4月24日 04:02:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/71983214.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定