dongmaqiu6084 2018-10-26 03:27
浏览 150

从go中的tcp连接读取数据是否需要for循环?

There's a func to handle tcp connection:

for {
    select {
    case conn := <-listen:
        go handleClient(conn)
    ...
}

func handleClient(client net.Conn) {
    for {
       // ...read from conn
       // at some point return
       return
    }
}

My question is , if you use for loop, you must write return or it will be a dead loop. If it returns, this handleClient function will execute only once. So for is not necessary here, right? We can still read all of the data Without for , is this the right way to think ?

  • 写回答

1条回答 默认 最新

  • dongpao5261 2018-10-26 11:10
    关注

    A common pattern for a server handling connections might be

    func handleClient(conn net.Conn) {
        r := bufio.NewReader(conn)
        for {
            line, err := r.ReadBytes(byte('
    '))
            switch err {
            case nil:
                break
            case io.EOF:
            default:
                fmt.Println("ERROR", err)
            }
            // do something with the data, in this case echo it back
            conn.Write(line)
        }
    }
    

    The for {} loop is necessary to read multiple lines of data from the connection.

    If the handleClient can read the input all in one chunk then a loop isn't necessary

    So, yes you are right the for {} is not always necessary but it depends what data is being read. Often a loop like this is the best way to read the data

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?