dosi8657 2014-08-24 06: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 08: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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?