gpt4 book ai didi

go - channel 卡住的 TCP 到 Redis 服务器

转载 作者:可可西里 更新时间:2023-11-01 11:14:59 32 4
gpt4 key购买 nike

我需要向redis服务器发送三次echo aaa,但它卡在过程中间,我也检查如果 readwrite 操作收到错误消息,但它没有。那么,为什么它会卡在进程中间?

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\r\n$4\r\necho\r\n$3\r\naaa\r\n"))
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...")
}

输出:

$3
aaa
$3
aaa
Stuck here...

最佳答案

readFromServer 函数从 isWrite channel 接收一个值,然后阻塞对 io.Copy 的调用。 io.Copy 函数直到 EOF 或读取或写入数据时出现错误才会返回。所有程序输出均来自对 io.Copy 的单次调用。

第二次发送到 isWrite 在 sendToServer block 中。isWrite channel 是一个无缓冲 channel 。在没有接收方之前,无缓冲 channel 上的发送不会继续。 channel 上没有接收器,因为 readFromServer 在调用 io.Copy 时被阻塞。

可能的修复是:

  • 解决方法是修改 readFromServer 以解析 RESP 协议(protocol),并在循环中每次迭代只读取一条消息。

  • 将 readFromServer 中的 for 循环替换为对 io.Copy 的单个调用。

不需要 isWrite channel 。

该程序不确保 readFromServer 在程序退出前读取所有来自 writeToServer 的响应。

关于go - channel 卡住的 TCP 到 Redis 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52467359/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com