1
0
mirror of https://github.com/fumiama/WireGold.git synced 2026-06-05 07:50:24 +08:00

optimize(p2p): tcp pdu

This commit is contained in:
源文雨
2025-02-25 22:11:30 +09:00
parent 9f36504635
commit 489537d152
2 changed files with 8 additions and 18 deletions

View File

@@ -1,18 +1,14 @@
package tcp package tcp
import ( import (
"bytes"
"encoding/binary" "encoding/binary"
"errors" "errors"
"io" "io"
"net" "net"
"runtime"
"time" "time"
"github.com/fumiama/WireGold/config" "github.com/fumiama/WireGold/config"
"github.com/fumiama/WireGold/helper" "github.com/fumiama/WireGold/helper"
"github.com/fumiama/orbyte"
"github.com/fumiama/orbyte/pbuf"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@@ -37,19 +33,16 @@ var (
type packet struct { type packet struct {
typ packetType typ packetType
len uint16 len uint16
dat pbuf.Bytes dat []byte
io.ReaderFrom io.ReaderFrom
io.WriterTo io.WriterTo
} }
func (p *packet) pack() (net.Buffers, func()) { func (p *packet) pack() *net.Buffers {
d := helper.NewWriterF(func(w *helper.Writer) { return &net.Buffers{magicbuf, helper.NewWriterF(func(w *helper.Writer) {
w.WriteByte(byte(p.typ)) w.WriteByte(byte(p.typ))
w.WriteUInt16(p.len) w.WriteUInt16(p.len)
}) }).Trans().Bytes(), p.dat}
return net.Buffers{magicbuf, d.Bytes(), p.dat.Bytes()}, func() {
runtime.KeepAlive(d)
}
} }
func (p *packet) Read(_ []byte) (int, error) { func (p *packet) Read(_ []byte) (int, error) {
@@ -87,14 +80,12 @@ func (p *packet) ReadFrom(r io.Reader) (n int64, err error) {
if err != nil { if err != nil {
return return
} }
p.dat = pbuf.BufferItemToBytes((*orbyte.Item[bytes.Buffer])(w).Trans()) p.dat = w.TransBytes()
return return
} }
func (p *packet) WriteTo(w io.Writer) (n int64, err error) { func (p *packet) WriteTo(w io.Writer) (n int64, err error) {
buf, cl := p.pack() return io.Copy(w, p.pack())
defer cl()
return io.Copy(w, &buf)
} }
func isvalid(tcpconn *net.TCPConn, timeout time.Duration) (issub, ok bool) { func isvalid(tcpconn *net.TCPConn, timeout time.Duration) (issub, ok bool) {

View File

@@ -14,7 +14,6 @@ import (
"github.com/fumiama/WireGold/config" "github.com/fumiama/WireGold/config"
"github.com/fumiama/WireGold/gold/p2p" "github.com/fumiama/WireGold/gold/p2p"
"github.com/fumiama/orbyte/pbuf"
) )
type EndPoint struct { type EndPoint struct {
@@ -378,7 +377,7 @@ func (conn *Conn) ReadFromPeer(b []byte) (int, p2p.EndPoint, error) {
break break
} }
} }
n := copy(b, p.pckt.dat.Bytes()) n := copy(b, p.pckt.dat)
return n, p.addr, nil return n, p.addr, nil
} }
@@ -452,7 +451,7 @@ RECONNECT:
cnt, err := io.Copy(tcpconn, &packet{ cnt, err := io.Copy(tcpconn, &packet{
typ: packetTypeNormal, typ: packetTypeNormal,
len: uint16(len(b)), len: uint16(len(b)),
dat: pbuf.ParseBytes(b...), dat: b,
}) })
if err != nil { if err != nil {
if subc == nil { if subc == nil {