英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论