Exemple #1
0
func putBufioWriter(bw *bufio.Writer) {
	bw.Reset(nil)
	if pool := bufioWriterPool(bw.Available()); pool != nil {
		pool.Put(bw)
	}
}
Exemple #2
0
func WritePacket(writer *bufio.Writer, pk *Packet) error {
	if writer == nil {
		return errors.New("No writer")
	}
	if writer.Available() == 0 {
		return errors.New("Writer not available")
	}
	if pk.LengthPayload == 0 {
		pk.LengthPayload = uint32(len(pk.Payload))
	}
	if pk.LengthText == 0 {
		pk.LengthText = uint32(len([]byte(pk.Text)))
	}
	// write Header
	pk.Flag = pk.Flag | lengthToPow(pk.LengthPayload) | (lengthToPow(pk.LengthText) << 2)

	// write Flag
	if err := binary.Write(writer, binary.BigEndian, pk.Flag); err != nil {
		return err
	}

	// write text length
	if err := writeLength(writer, pk.LengthText); err != nil {
		return err
	}

	// write payload length
	if err := writeLength(writer, pk.LengthPayload); err != nil {
		return err
	}

	// TODO calc CRC16
	var crc16 uint16
	// write Seq
	if err := binary.Write(writer, binary.BigEndian, crc16); err != nil {
		return err
	}

	// write Seq
	if err := binary.Write(writer, binary.BigEndian, pk.Seq); err != nil {
		return err
	}

	// write Text
	if _, err := writer.WriteString(pk.Text); err != nil {
		return err
	}

	// flush first
	// MTU = 576
	// IP = 20
	// TCP = 20
	// XBP = 5 - 13
	// 576-20-20-13
	if pk.LengthPayload+pk.LengthText > 523 {
		// flush header first
		if err := writer.Flush(); err != nil {
			return err
		}
	}
	// TODO make Big payload write more effecient
	// write Payload
	if _, err := writer.Write(pk.Payload); err != nil {
		return err
	}
	return writer.Flush()
}