示例#1
0
文件: compress.go 项目: cnhup/httpmq
func acquireFlateWriter(w io.Writer, level int) *flateWriter {
	p := flateWriterPoolMap[level]
	if p == nil {
		panic(fmt.Sprintf("BUG: unexpected compression level passed: %d. See compress/flate for supported levels", level))
	}

	v := p.Get()
	if v == nil {
		zw, err := zlib.NewWriterLevel(w, level)
		if err != nil {
			panic(fmt.Sprintf("BUG: unexpected error in zlib.NewWriterLevel(%d): %s", level, err))
		}
		return &flateWriter{
			Writer: zw,
			p:      p,
		}
	}
	zw := v.(*flateWriter)
	zw.Reset(w)
	return zw
}
示例#2
0
文件: client.go 项目: McStork/beats
// Send sends all data without waiting for ACK
func (c *Client) Send(data []interface{}) error {
	if len(data) == 0 {
		return nil
	}

	// 1. create window message
	c.wb.Reset()
	_, _ = c.wb.Write(codeWindowSize)
	writeUint32(c.wb, uint32(len(data)))

	// 2. serialize data (payload)
	if c.opts.compressLvl > 0 {
		// Compressed Data Frame:
		// version: uint8 = '2'
		// code: uint8 = 'C'
		// payloadSz: uint32
		// payload: compressed payload

		_, _ = c.wb.Write(codeCompressed) // write compressed header

		offSz := c.wb.Len()
		_, _ = c.wb.Write(empty4)
		offPayload := c.wb.Len()

		// compress payload
		w, err := zlib.NewWriterLevel(c.wb, c.opts.compressLvl)
		if err != nil {
			return err
		}

		if err := c.serialize(w, data); err != nil {
			return err
		}

		if err := w.Close(); err != nil {
			return err
		}

		// write compress header
		payloadSz := c.wb.Len() - offPayload
		binary.BigEndian.PutUint32(c.wb.Bytes()[offSz:], uint32(payloadSz))
	} else {
		if err := c.serialize(c.wb, data); err != nil {
			return err
		}
	}

	// 3. send buffer
	if err := c.setWriteDeadline(); err != nil {
		return nil
	}
	payload := c.wb.Bytes()
	for len(payload) > 0 {
		n, err := c.conn.Write(payload)
		if err != nil {
			return err
		}

		payload = payload[n:]
	}

	return nil
}