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个连接,内存很快就飙高了。
有疑问加站长微信联系(非本文作者)