dongpingwu8378 2017-03-23 14:52
浏览 61

在go http处理程序中使用goroutine和channel使ResponseWriter被阻止

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
)

var ch chan bool

func testTimer1() {
    go func() {
        log.Println("test timer 1")
        ch <- true
    }()

}

func timer1() {
    timer1 := time.NewTicker(2 * time.Second)
    select {
    case <-timer1.C:
        testTimer1()
    }

}

func myhandler(w http.ResponseWriter, r *http.Request) {
    for {
        go timer1()

        a := <-ch
        log.Println("get a: ", a)
        fmt.Fprintf(w, "hello world!!!!", a)
    }

    log.Println("test for break")
}

func main() {
    ch = make(chan bool)
    http.HandleFunc("/", myhandler)
    http.ListenAndServe(":8080", nil)
}

I wrote the above code, put a channel into "myhandler", channel will be given a bool data when the

timer task executed.

then I get the data from channel and write "hello world" into http writer

but I found the client couldn't receive the "hello world", the writer has been blocked!!!!!

Any one knows about this?

looks the running pic on my cmd: enter image description here

enter image description here

  • 写回答

2条回答 默认 最新

  • dpnzf48660 2017-03-23 16:26
    关注

    The for loop is an infinite loop so printing to the ResponseWriter is not "scheduled" to happen. If you want a comet-like approack (or long-polling URL) you may want to try this method.

    There's also a leak of tickers in timer1(). According to the Go Docs:

    Stop the ticker to release associated resources.

    You're always creating a new ticker every time you call go timer1() and the ticker is never closed so every new ticker just adds-up.

    评论

报告相同问题?

悬赏问题

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