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 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题