예제 #1
0
func (c *client) NextReader() (*parser.PacketDecoder, error) {
	if c.state != stateNormal {
		return nil, io.EOF
	}
	if c.payloadDecoder != nil {
		ret, err := c.payloadDecoder.Next()
		if err != io.EOF {
			return ret, err
		}
		c.getResp.Body.Close()
		c.payloadDecoder = nil
	}
	req := c.getReq()
	req.Method = "GET"
	var err error
	c.getResp, err = c.client.Do(req)
	if err != nil {
		return nil, err
	}
	if c.resp == nil {
		c.resp = c.getResp
	}
	c.payloadDecoder = parser.NewPayloadDecoder(c.getResp.Body)
	return c.payloadDecoder.Next()
}
예제 #2
0
func (p *Polling) post(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html")
	if !p.postLocker.TryLock() {
		http.Error(w, "overlay post", http.StatusBadRequest)
		return
	}
	if p.getState() != stateNormal {
		http.Error(w, "closed", http.StatusBadRequest)
		return
	}

	defer func() {
		if p.getState() == stateClosing {
			if p.getLocker.TryLock() {
				p.setState(stateClosed)
				p.callback.OnClose(p)
				p.getLocker.Unlock()
			}
		}
		p.postLocker.Unlock()
	}()

	var decoder *parser.PayloadDecoder
	if j := r.URL.Query().Get("j"); j != "" {
		// JSONP Polling
		d := r.FormValue("d")
		decoder = parser.NewPayloadDecoder(bytes.NewBufferString(d))
	} else {
		// XHR Polling
		decoder = parser.NewPayloadDecoder(r.Body)
	}
	for {
		d, err := decoder.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		p.callback.OnPacket(d)
		d.Close()
	}
	w.Write([]byte("ok"))
}