Go bufio.Scanner 在读取到 Redis 的 TCP 连接时停止

使用读取Redis服务器之间的TCP连接 bufio.Scanner


fmt.Fprintf(conn, "*3\r\n$3\r\nSET\r\n$5\r\nmykey\r\n$7\r\nHello!!\r\n")

scanner := bufio.NewScanner(conn)

for {

    // fmt.Println("marker00")

    if ok := scanner.Scan(); !ok {

        // fmt.Println("marker01")

        break

    }

    // fmt.Println("marker02")

    fmt.Println(scanner.Text())

}

“+OK”作为第一次扫描的结果出现,但第二次扫描仅在调用Scan方法中停止。(marker00 -> marker02 -> marker00 不再输出)


为什么会Scan停止,我如何知道 TCP 响应的结束(不使用bufio.Reader)?


jeck猫
浏览 315回答 2
2回答

UYOU

Redis 在发送命令后不会为您关闭连接。Scan() 在未发送的 io.EOF 之后结束。看看这个:package mainimport (&nbsp; &nbsp; "bufio"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "net")// before go run, you must hit `redis-server` to wake redis upfunc main() {&nbsp; &nbsp; conn, _ := net.Dial("tcp", "localhost:6379")&nbsp; &nbsp; message := "*3\r\n$3\r\nSET\r\n$1\r\na\r\n$1\r\nb\r\n"&nbsp; &nbsp; go func(conn net.Conn) {&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < 10; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintf(conn, message)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }(conn)&nbsp; &nbsp; scanner := bufio.NewScanner(conn)&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; if ok := scanner.Scan(); !ok {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(scanner.Text())&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("Scanning ended")}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go