Skip to content

Commit

Permalink
reuse []byte in websocket (#64)
Browse files Browse the repository at this point in the history
* ues pbytes to reues []byte
  • Loading branch information
Allenxuxu authored Mar 14, 2021
1 parent 3519ef9 commit e1348b1
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
10 changes: 8 additions & 2 deletions plugins/websocket/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@ import (
"github.com/Allenxuxu/gev/log"
"github.com/Allenxuxu/gev/plugins/websocket/ws"
"github.com/Allenxuxu/ringbuffer"
"github.com/gobwas/pool/pbytes"
)

const upgradedKey = "gev_ws_upgraded"
const (
upgradedKey = "gev_ws_upgraded"
headerbufferKey = "gev_header_buf"
)

// Protocol websocket
type Protocol struct {
Expand All @@ -30,8 +34,10 @@ func (p *Protocol) UnPacket(c *connection.Connection, buffer *ringbuffer.RingBuf
return
}
c.Set(upgradedKey, true)
c.Set(headerbufferKey, pbytes.Get(0, ws.MaxHeaderSize-2))
} else {
header, err := ws.VirtualReadHeader(buffer)
bts, _ := c.Get(headerbufferKey)
header, err := ws.VirtualReadHeader(bts.([]byte), buffer)
if err != nil {
if err != ws.ErrHeaderNotReady {
log.Error(err)
Expand Down
5 changes: 5 additions & 0 deletions plugins/websocket/wrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"github.com/Allenxuxu/gev/log"
"github.com/Allenxuxu/gev/plugins/websocket/ws"
"github.com/Allenxuxu/gev/plugins/websocket/ws/util"
"github.com/gobwas/pool/pbytes"
)

// WSHandler WebSocket Server 注册接口
Expand Down Expand Up @@ -91,4 +92,8 @@ func (s *HandlerWrap) OnMessage(c *connection.Connection, ctx interface{}, paylo
// OnClose wrap
func (s *HandlerWrap) OnClose(c *connection.Connection) {
s.wsHandler.OnClose(c)

if bts, ok := c.Get(headerbufferKey); ok {
pbytes.Put(bts.([]byte))
}
}
6 changes: 2 additions & 4 deletions plugins/websocket/ws/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (

"github.com/Allenxuxu/ringbuffer"
"github.com/Allenxuxu/toolkit/convert"
"github.com/gobwas/pool/pbytes"
)

// Errors used by frame reader.
Expand All @@ -17,14 +16,13 @@ var (
)

// VirtualReadHeader reads a frame header from r.
func VirtualReadHeader(in *ringbuffer.RingBuffer) (h Header, err error) {
func VirtualReadHeader(bts []byte, in *ringbuffer.RingBuffer) (h Header, err error) {
if in.Length() < 6 {
err = ErrHeaderNotReady
return
}

bts := pbytes.Get(2, MaxHeaderSize-2)
defer pbytes.Put(bts)
bts = bts[:2]
// Prepare to hold first 2 bytes to choose size of next read.
_, _ = in.VirtualRead(bts)

Expand Down

0 comments on commit e1348b1

Please sign in to comment.