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个连接,内存很快就飙高了。
更多评论
不管超时还是拿到数据,都会Close掉这个连接
这里并非如此
select中的break只是break了select,没有break for循环。而且,select中是不需要break的(默认行为)
实际上,按你说的,根本没必要存在这个for循环。
#1