1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2025-01-03 07:56:42 -05:00
This commit is contained in:
Darien Raymond 2017-04-19 18:00:11 +02:00
parent 0ebebfa458
commit 1d761e30a9
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169

View File

@ -1,6 +1,8 @@
package mux package mux
import ( import (
"runtime"
"v2ray.com/core/common/buf" "v2ray.com/core/common/buf"
"v2ray.com/core/common/net" "v2ray.com/core/common/net"
"v2ray.com/core/common/serial" "v2ray.com/core/common/serial"
@ -30,7 +32,7 @@ func NewResponseWriter(id uint16, writer buf.Writer) *Writer {
} }
} }
func (w *Writer) writeInternal(mb buf.MultiBuffer) error { func (w *Writer) getNextFrameMeta() FrameMetadata {
meta := FrameMetadata{ meta := FrameMetadata{
SessionID: w.id, SessionID: w.id,
Target: w.dest, Target: w.dest,
@ -42,35 +44,51 @@ func (w *Writer) writeInternal(mb buf.MultiBuffer) error {
meta.SessionStatus = SessionStatusNew meta.SessionStatus = SessionStatusNew
} }
hasData := !mb.IsEmpty() return meta
}
if hasData { func (w *Writer) writeMetaOnly() error {
meta.Option.Add(OptionData) meta := w.getNextFrameMeta()
b := buf.New()
if err := b.AppendSupplier(meta.AsSupplier()); err != nil {
return err
} }
runtime.KeepAlive(meta)
return w.writer.Write(buf.NewMultiBufferValue(b))
}
func (w *Writer) writeData(mb buf.MultiBuffer) error {
meta := w.getNextFrameMeta()
meta.Option.Add(OptionData)
frame := buf.New() frame := buf.New()
frame.AppendSupplier(meta.AsSupplier()) if err := frame.AppendSupplier(meta.AsSupplier()); err != nil {
return err
}
runtime.KeepAlive(meta)
mb2 := buf.NewMultiBuffer() mb2 := buf.NewMultiBuffer()
mb2.Append(frame) mb2.Append(frame)
if hasData { if err := frame.AppendSupplier(serial.WriteUint16(uint16(mb.Len()))); err != nil {
frame.AppendSupplier(serial.WriteUint16(uint16(mb.Len()))) return err
mb2.AppendMulti(mb)
} }
mb2.AppendMulti(mb)
return w.writer.Write(mb2) return w.writer.Write(mb2)
} }
func (w *Writer) Write(mb buf.MultiBuffer) error { func (w *Writer) Write(mb buf.MultiBuffer) error {
if mb.IsEmpty() {
return w.writeMetaOnly()
}
const chunkSize = 8 * 1024 const chunkSize = 8 * 1024
for { for !mb.IsEmpty() {
slice := mb.SliceBySize(chunkSize) slice := mb.SliceBySize(chunkSize)
if err := w.writeInternal(slice); err != nil { if err := w.writeData(slice); err != nil {
return err return err
} }
if mb.IsEmpty() {
break
}
} }
return nil return nil
} }
@ -83,6 +101,7 @@ func (w *Writer) Close() {
frame := buf.New() frame := buf.New()
frame.AppendSupplier(meta.AsSupplier()) frame.AppendSupplier(meta.AsSupplier())
runtime.KeepAlive(meta)
w.writer.Write(buf.NewMultiBufferValue(frame)) w.writer.Write(buf.NewMultiBufferValue(frame))
} }