请教下大家,800连接内存涨的很快,代码这样有问题吗?

ericlee · 2013-04-02 07:14:06 · 5013 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2013-04-02 07:14:06 的主题,其中的信息可能已经有所发展或是发生改变。

func PollMessageHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userId := vars["userId"]
hj, ok := w.(http.Hijacker)
if !ok {
    errorMsg := "The Web Server does not support Hijacking! "
    http.Error(w, errorMsg, http.StatusInternalServerError)
    return
}
conn, bufrw, err := hj.Hijack()
if err != nil {
    errorMsg := "Internal error!"
    http.Error(w, errorMsg, http.StatusInternalServerError)
    return
}
client := &WebClient{userId, conn, bufrw, make(chan []byte)}
WebClientConn[userId] = client
common.Log(0, " Web Client ", userId, "...", len(WebClientConn))
go client.responseMessage()}

func (c *WebClient) responseMessage() {
for {
    select {
    case body := <-c.Send:
        c.Bufrw.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
        c.Bufrw.Write(body)
        common.Log(0, "------------------------------ To ", c.UserId)
        break
    case <-time.After(time.Second * 50):
        c.Bufrw.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
        c.Bufrw.Write([]byte("Timeout"))
        break
    }
}
c.Bufrw.Flush()
c.Conn.Close()}

请问这样不对吗?每次来了连接,丢到goroutine等待channel来消息或者超时。不管超时还是拿到数据,都会Close掉这个连接,我在客户端测试,800个连接,内存很快就飙高了。


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

5013 次点击  
加入收藏 微博
3 回复  |  直到 2013-04-11 11:47:14
polaris
polaris · #1 · 12年之前

不管超时还是拿到数据,都会Close掉这个连接

这里并非如此

select中的break只是break了select,没有break for循环。而且,select中是不需要break的(默认行为)

实际上,按你说的,根本没必要存在这个for循环。

ericlee
ericlee · #2 · 12年之前

嗯,明白了,select 如果没有default的时候,是阻塞的,不需要for来死循环,所以杯具了。 谢谢。。。

whispermemory
whispermemory · #3 · 12年之前

good

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传