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

时间:2012-03-13 08:51:10

标签: tcp go

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

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

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

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

1 个答案:

答案 0 :(得分: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.
  }
}
相关问题