我怎样才能使net.Read等待golang的输入?

Håk*_*kon 9 tcp go

所以我在Go中为我的电梯制作服务器,并且我正在运行函数"handler"作为带有TCP连接的goroutine.我希望它从连接中读取,如果在某个时间跨度内没有检测到信号,我希望它返回错误.

func handler(conn net.Conn){
    conn.SetReadTimeout(5e9)
    for{
        data := make([]byte, 512)
        _,err := conn.Read(data)
    }
}
Run Code Online (Sandbox Code Playgroud)

只要我有一个客户端通过连接发送东西它似乎工作正常,但一旦客户端停止发送net.Read函数返回错误EOF并开始循环没有任何延迟.

这可能是Read应该如何工作,但是有人可以建议另一种方法来处理问题,而不必每次我想读取东西时都关闭并打开连接吗?

Jer*_*all 20

我认为阅读正在按预期工作.听起来你想要net.Read就像Go中的频道一样工作.这很简单,只需将net.Re包在一个正在运行的goroutine中并使用select从通道读取goroutine非常便宜,因此是一个通道

例:

ch := make(chan []byte)
eCh := make(chan error)

// Start a goroutine to read from our net connection
go func(ch chan []byte, eCh chan error) {
  for {
    // try to read the data
    data := make([]byte, 512)
    _,err := conn.Read(data)
    if err != nil {
      // send an error if it's encountered
      eCh<- err
      return
    }
    // send data if we read some.
    ch<- data
  }
}(ch, eCh)

ticker := time.Tick(time.Second)
// continuously read from the connection
for {
  select {
     // This case means we recieved data on the connection
     case data := <-ch:
       // Do something with the data
     // This case means we got an error and the goroutine has finished
     case err := <-eCh:
       // handle our error then exit for loop
       break;
     // This will timeout on the read.
     case <-ticker:
       // do nothing? this is just so we can time out if we need to.
       // you probably don't even need to have this here unless you want
       // do something specifically on the timeout.
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 文档明确警告不要以这种方式使用[`time.Tick`](https://golang.org/pkg/time/#Tick). (2认同)