dosi8657 2014-08-23 22:44
浏览 72
已采纳

进入bufio.Scanner在读取与Redis的TCP连接时停止

Reading TCP connection between Redis-server by using bufio.Scanner

fmt.Fprintf(conn, "*3
$3
SET
$5
mykey
$7
Hello!!
")
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" comes as the result for first scanning, but the second scanning stops just in invoking Scan method. (marker00 -> marker02 -> marker00 and no output any more)

Why does Scan stop and how can I know the end of TCP response (without using bufio.Reader)?

  • 写回答

2条回答 默认 最新

  • dsfs504545 2014-08-24 00:03
    关注

    Redis does not close the connection for you after sending a command. Scan() ends after io.EOF which is not sent.

    Check out this:

    package main
    
    import (
        "bufio"
        "fmt"
        "net"
    )
    
    // before go run, you must hit `redis-server` to wake redis up
    func main() {
        conn, _ := net.Dial("tcp", "localhost:6379")
        message := "*3
    $3
    SET
    $1
    a
    $1
    b
    "
    
        go func(conn net.Conn) {
            for i := 0; i < 10; i++ {
                fmt.Fprintf(conn, message)
            }
        }(conn)
    
        scanner := bufio.NewScanner(conn)
        for {
            if ok := scanner.Scan(); !ok {
                break
            }
            fmt.Println(scanner.Text())
        }
        fmt.Println("Scanning ended")
    }
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部