Пример #1
0
func (c *NetConn) write(pkt packet.Packet) error {
	// reset and eventually grow buffer
	packetLength := pkt.Len()
	c.sendBuffer.Reset()
	c.sendBuffer.Grow(packetLength)
	buf := c.sendBuffer.Bytes()[0:packetLength]

	// encode packet
	_, err := pkt.Encode(buf)
	if err != nil {
		c.conn.Close()
		return newTransportError(EncodeError, err)
	}

	// write buffer
	bytesWritten, err := c.writer.Write(buf)
	if isCloseError(err) {
		return newTransportError(ConnectionClose, err)
	} else if err != nil {
		c.conn.Close()
		return newTransportError(NetworkError, err)
	}

	// increment write counter
	atomic.AddInt64(&c.writeCounter, int64(bytesWritten))

	return nil
}
Пример #2
0
func (c *WebSocketConn) write(pkt packet.Packet) error {
	// reset and eventually grow buffer
	packetLength := pkt.Len()
	c.sendBuffer.Reset()
	c.sendBuffer.Grow(packetLength)
	buf := c.sendBuffer.Bytes()[0:packetLength]

	// encode packet
	n, err := pkt.Encode(buf)
	if err != nil {
		c.end(false, websocket.CloseInternalServerErr)
		return newTransportError(EncodeError, err)
	}

	// create writer if missing
	if c.writer == nil {
		writer, err := c.conn.NextWriter(websocket.BinaryMessage)
		if err != nil {
			c.end(false, websocket.CloseInternalServerErr)
			return newTransportError(NetworkError, err)
		}

		c.writer = writer
	}

	// write packet to writer
	_, err = c.writer.Write(buf)
	if isCloseError(err) {
		return newTransportError(ConnectionClose, err)
	} else if err != nil {
		c.end(false, websocket.CloseInternalServerErr)
		return newTransportError(NetworkError, err)
	}

	// increment write counter
	atomic.AddInt64(&c.writeCounter, int64(n))

	return nil
}