mirror of
https://github.com/zhaojh329/rttys.git
synced 2026-02-27 09:53:21 +08:00
use sync.Pool for WebSocket read buffers in http proxy
Introduce a buffer pool to reduce memory allocations during WebSocket handling. Previously, each WebSocket connection created a new 4KB buffer for every read operation. This reduces GC pressure and improves memory efficiency for WebSocket traffic. Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
This commit is contained in:
19
http.go
19
http.go
@@ -104,6 +104,18 @@ func httpProxySessionsClean() {
|
||||
}
|
||||
}
|
||||
|
||||
var httpBufPool = sync.Pool{
|
||||
New: func() any {
|
||||
return &HttpBuf{
|
||||
buf: make([]byte, 1024*32),
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
type HttpBuf struct {
|
||||
buf []byte
|
||||
}
|
||||
|
||||
func doHttpProxy(srv *RttyServer, c net.Conn) {
|
||||
defer logPanic()
|
||||
defer c.Close()
|
||||
@@ -168,14 +180,15 @@ func doHttpProxy(srv *RttyServer, c net.Conn) {
|
||||
hpw.WriteRequest(req)
|
||||
|
||||
if req.Header.Get("Upgrade") == "websocket" {
|
||||
b := make([]byte, 4096)
|
||||
hb := httpBufPool.Get().(*HttpBuf)
|
||||
defer httpBufPool.Put(hb)
|
||||
|
||||
for {
|
||||
n, err := c.Read(b)
|
||||
n, err := c.Read(hb.buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
sendHttpReq(dev, ses.https, hpw.srcAddr[:], destAddr, b[:n])
|
||||
sendHttpReq(dev, ses.https, hpw.srcAddr[:], destAddr, hb.buf[:n])
|
||||
ses.Expire()
|
||||
}
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user