v2ray-core/transport/internet/kcp/output.go

80 lines
1.5 KiB
Go
Raw Normal View History

2016-06-27 20:52:48 +00:00
package kcp
import (
2016-06-29 08:34:34 +00:00
"io"
2016-06-27 20:52:48 +00:00
"sync"
"github.com/v2ray/v2ray-core/common/alloc"
v2io "github.com/v2ray/v2ray-core/common/io"
2016-08-06 19:59:22 +00:00
"github.com/v2ray/v2ray-core/transport/internet"
2016-06-27 20:52:48 +00:00
)
2016-07-02 19:26:50 +00:00
type SegmentWriter interface {
2016-07-04 12:17:42 +00:00
Write(seg Segment)
2016-07-02 19:26:50 +00:00
}
type BufferedSegmentWriter struct {
2016-06-27 20:52:48 +00:00
sync.Mutex
mtu uint32
buffer *alloc.Buffer
writer v2io.Writer
}
2016-07-02 19:26:50 +00:00
func NewSegmentWriter(writer *AuthenticationWriter) *BufferedSegmentWriter {
return &BufferedSegmentWriter{
2016-07-02 06:45:31 +00:00
mtu: writer.Mtu(),
2016-06-27 20:52:48 +00:00
writer: writer,
}
}
2016-07-04 12:17:42 +00:00
func (this *BufferedSegmentWriter) Write(seg Segment) {
2016-06-27 20:52:48 +00:00
this.Lock()
defer this.Unlock()
nBytes := seg.ByteSize()
if uint32(this.buffer.Len()+nBytes) > this.mtu {
this.FlushWithoutLock()
}
if this.buffer == nil {
2016-07-17 10:59:57 +00:00
this.buffer = alloc.NewLocalBuffer(2048).Clear()
2016-06-27 20:52:48 +00:00
}
2016-07-05 12:08:08 +00:00
this.buffer.Value = seg.Bytes(this.buffer.Value)
2016-06-27 20:52:48 +00:00
}
2016-07-02 19:26:50 +00:00
func (this *BufferedSegmentWriter) FlushWithoutLock() {
2016-07-12 15:37:12 +00:00
go this.writer.Write(this.buffer)
2016-06-27 20:52:48 +00:00
this.buffer = nil
}
2016-07-02 19:26:50 +00:00
func (this *BufferedSegmentWriter) Flush() {
2016-06-27 20:52:48 +00:00
this.Lock()
defer this.Unlock()
if this.buffer.Len() == 0 {
return
}
this.FlushWithoutLock()
}
2016-06-29 08:34:34 +00:00
type AuthenticationWriter struct {
2016-08-06 19:59:22 +00:00
Authenticator internet.Authenticator
2016-06-29 08:34:34 +00:00
Writer io.Writer
}
func (this *AuthenticationWriter) Write(payload *alloc.Buffer) error {
defer payload.Release()
this.Authenticator.Seal(payload)
_, err := this.Writer.Write(payload.Value)
return err
}
func (this *AuthenticationWriter) Release() {}
2016-07-02 06:45:31 +00:00
func (this *AuthenticationWriter) Mtu() uint32 {
2016-08-06 19:59:22 +00:00
return effectiveConfig.Mtu - uint32(this.Authenticator.Overhead())
2016-07-02 06:45:31 +00:00
}