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条)

报告相同问题?

悬赏问题

  • ¥20 eclipse连接sap后代码跑出来空白
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi