tcp - 如何让 net.Read 等待 golang 中的输入?

标签 tcp go

所以我在 Go 中为我的电梯制作了一个服务器,并且我正在运行函数“处理程序”作为带有 TCP 连接的 goroutine。 我希望它从连接中读取,如果在特定时间跨度内未检测到信号,我希望它返回错误。

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

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

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

最佳答案

我认为,Read 正在按预期工作。听起来您希望 net.Read 像 Go 中的 channel 一样工作。这在 go 中非常简单,只需包装网络即可。在正在运行的 goroutine 中读取并使用 select 从 channel 中读取 goroutine 真的很便宜, channel 也是如此

例子:

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.
  }
}

关于tcp - 如何让 net.Read 等待 golang 中的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9680812/

相关文章:

c++ - 从套接字读取和转换字节 C++ 的最快方法

session - 想要在客户端发送新请求时获取 session 值

go - 为什么Go编程中没有while循环?试图让用户输入数字1到12?

pointers - 返回给函数的调用者时无法保留 golang 字段的值

go - 获取 slice 的所有排列

C++ 发送和接收 TCP/IP 结构

javascript - 从 Firefox 插件打开 TCP 套接字

string - Erlang:将 TCP 发送的字符串转换为正确的形式,例如<<"SomeString">> 到 "SomeString"?

c# - 使用 .net 监控传入/传出的 http 流量

function - 在另一个包中定义函数