1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-17 09:56:18 -05:00
v2fly/transport/internet/kcp/output.go

56 lines
965 B
Go
Raw Normal View History

2019-02-01 14:08:21 -05:00
// +build !confonly
2016-06-27 16:52:48 -04:00
package kcp
import (
2016-06-29 04:34:34 -04:00
"io"
2016-06-27 16:52:48 -04:00
"sync"
2021-02-16 15:31:50 -05:00
"github.com/v2fly/v2ray-core/v4/common/buf"
"github.com/v2fly/v2ray-core/v4/common/retry"
2016-06-27 16:52:48 -04:00
)
2016-07-02 15:26:50 -04:00
type SegmentWriter interface {
2016-12-20 16:53:58 -05:00
Write(seg Segment) error
2016-07-02 15:26:50 -04:00
}
2016-12-20 16:53:58 -05:00
type SimpleSegmentWriter struct {
2016-06-27 16:52:48 -04:00
sync.Mutex
2016-12-09 05:35:27 -05:00
buffer *buf.Buffer
2016-12-08 10:27:41 -05:00
writer io.Writer
2016-06-27 16:52:48 -04:00
}
2016-12-20 16:53:58 -05:00
func NewSegmentWriter(writer io.Writer) SegmentWriter {
return &SimpleSegmentWriter{
2016-06-27 16:52:48 -04:00
writer: writer,
2017-04-15 15:19:21 -04:00
buffer: buf.New(),
2016-06-27 16:52:48 -04:00
}
}
2017-09-19 17:27:49 -04:00
func (w *SimpleSegmentWriter) Write(seg Segment) error {
w.Lock()
defer w.Unlock()
2016-06-27 16:52:48 -04:00
2018-11-02 16:34:04 -04:00
w.buffer.Clear()
rawBytes := w.buffer.Extend(seg.ByteSize())
seg.Serialize(rawBytes)
2017-09-19 17:27:49 -04:00
_, err := w.writer.Write(w.buffer.Bytes())
2016-12-20 16:53:58 -05:00
return err
2016-06-27 16:52:48 -04:00
}
2017-09-19 17:27:49 -04:00
type RetryableWriter struct {
writer SegmentWriter
}
func NewRetryableWriter(writer SegmentWriter) SegmentWriter {
return &RetryableWriter{
writer: writer,
}
}
func (w *RetryableWriter) Write(seg Segment) error {
return retry.Timed(5, 100).On(func() error {
return w.writer.Write(seg)
})
}