doupacan2098 2018-09-23 15:01
浏览 128
已采纳

TCP到Redis服务器且通道卡死

I need to send echo aaa three times to redis server, but its get stuck in the middle of process, I also check if read and write operation get error message, but it doesn't. so, why it get stuck in the middle of process?

package main



import (
    "fmt"
    "os"
    "io"
    "net"
    "sync"
)

var (
    wg = new(sync.WaitGroup)
)

func readFromServer(isWrite chan bool, r io.Reader) {
    for {
        select {
        case <-isWrite:
            _ , err := io.Copy(os.Stdout, r)
            if err != nil {
                panic(err)
            }
        }
    }
}

func writeToServer(conn net.Conn , isWrite chan bool ){
    defer wg.Done()
    for i :=0; i<3; i++{
        _ , err := conn.Write([]byte("*2
$4
echo
$3
aaa
"))
        if err != nil {
            panic(err)
        }
        isWrite<- true
    }
}

func main(){
    wg.Add(1)

    conn ,err := net.Dial("tcp","127.0.0.1:6379")
    isWrite := make(chan bool)

    if err != nil {
        panic(err)
    }

    go readFromServer(isWrite, conn)
    go writeToServer(conn , isWrite)



    wg.Wait()
    fmt.Println("finished...")
}

Output:

$3
aaa
$3
aaa
Stuck here...
  • 写回答

1条回答 默认 最新

  • drci47425 2018-09-23 15:18
    关注

    The readFromServer function receives one value from the isWrite channel and then blocks in the call to io.Copy. The io.Copy function does not return until EOF or some error reading or writing data. All of the program output is from the single call to io.Copy.

    The second send to isWrite in sendToServer blocks. The isWrite channel is an unbuffered channel. A send on an unbuffered channel does not proceed until there's a receiver. There is no receiver on the channel because readFromServer is blocked in the call to io.Copy.

    Possible fixes are:

    • The fix is to modify readFromServer to parse the RESP protocol and read exactly one message per iteration in the loop.

    • Replace for loop in readFromServer with a single call to io.Copy.

    The isWrite channel is not needed.

    The program does not ensure that readFromServer reads all of the responses from writeToServer before the program exits.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试