Skip to content

Commit f55a412

Browse files
committed
Add SetBufferThreshold Method
1 parent c96b189 commit f55a412

13 files changed

+192
-302
lines changed

.golangci.yaml

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ linters:
33
# Disable specific linter
44
# https://golangci-lint.run/usage/linters/#disabled-by-default
55
disable:
6+
- mnd
67
- testpackage
7-
- nosnakecase
88
- nlreturn
99
- gomnd
1010
- forcetypeassert
@@ -14,15 +14,13 @@ linters:
1414
- ineffassign
1515
- lll
1616
- funlen
17-
- scopelint
1817
- dupl
1918
- gofumpt
2019
- gofmt
2120
- godot
2221
- gci
2322
- goimports
2423
- gocognit
25-
- ifshort
2624
- gochecknoinits
2725
- goconst
2826
- depguard

client.go

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@ import (
1616
)
1717

1818
// Dialer 拨号器接口
19-
// dialer interface
19+
// Dialer interface
2020
type Dialer interface {
2121
// Dial 连接到指定网络上的地址
22-
// connects to the address on the named network
22+
// Connects to the address on the named network
2323
Dial(network, addr string) (c net.Conn, err error)
2424
}
2525

@@ -31,7 +31,7 @@ type connector struct {
3131
}
3232

3333
// NewClient 创建一个新的 WebSocket 客户端连接
34-
// creates a new WebSocket client connection
34+
// Creates a new WebSocket client connection
3535
func NewClient(handler Event, option *ClientOption) (*Conn, *http.Response, error) {
3636
option = initClientOption(option)
3737
c := &connector{option: option, eventHandler: handler}
@@ -84,7 +84,7 @@ func NewClientFromConn(handler Event, option *ClientOption, conn net.Conn) (*Con
8484
return client, resp, err
8585
}
8686

87-
// request 发送HTTP请求, 即WebSocket握手
87+
// 发送HTTP请求, 即WebSocket握手
8888
// Sends an http request, i.e., websocket handshake
8989
func (c *connector) request() (*http.Response, *bufio.Reader, error) {
9090
_ = c.conn.SetDeadline(time.Now().Add(c.option.HandshakeTimeout))
@@ -138,7 +138,7 @@ func (c *connector) request() (*http.Response, *bufio.Reader, error) {
138138
return resp, br, err
139139
}
140140

141-
// getPermessageDeflate 获取压缩拓展结果
141+
// 获取压缩拓展结果
142142
// Get compression expansion results
143143
func (c *connector) getPermessageDeflate(extensions string) PermessageDeflate {
144144
serverPD := permessageNegotiation(extensions)
@@ -157,8 +157,8 @@ func (c *connector) getPermessageDeflate(extensions string) PermessageDeflate {
157157
return pd
158158
}
159159

160-
// handshake 执行 WebSocket 握手操作
161-
// performs the WebSocket handshake operation
160+
// 执行 WebSocket 握手操作
161+
// Performs the WebSocket handshake operation
162162
func (c *connector) handshake() (*Conn, *http.Response, error) {
163163
resp, br, err := c.request()
164164
if err != nil {
@@ -202,8 +202,8 @@ func (c *connector) handshake() (*Conn, *http.Response, error) {
202202
return socket, resp, c.conn.SetDeadline(time.Time{})
203203
}
204204

205-
// getSubProtocol 从响应中获取子协议
206-
// retrieves the subprotocol from the response
205+
// 从响应中获取子协议
206+
// Retrieves the subprotocol from the response
207207
func (c *connector) getSubProtocol(resp *http.Response) (string, error) {
208208
a := internal.Split(c.option.RequestHeader.Get(internal.SecWebSocketProtocol.Key), ",")
209209
b := internal.Split(resp.Header.Get(internal.SecWebSocketProtocol.Key), ",")
@@ -214,8 +214,8 @@ func (c *connector) getSubProtocol(resp *http.Response) (string, error) {
214214
return subprotocol, nil
215215
}
216216

217-
// checkHeaders 检查响应头以验证握手是否成功
218-
// checks the response headers to verify if the handshake was successful
217+
// 检查响应头以验证握手是否成功
218+
// Checks the response headers to verify if the handshake was successful
219219
func (c *connector) checkHeaders(resp *http.Response) error {
220220
if resp.StatusCode != http.StatusSwitchingProtocols {
221221
return ErrHandshake

compress.go

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ import (
1414
"github.com/lxzan/gws/internal"
1515
)
1616

17-
// flateTail deflate压缩算法的尾部标记
18-
// the tail marker of the deflate compression algorithm
17+
// deflate压缩算法的尾部标记
18+
// The tail marker of the deflate compression algorithm
1919
var flateTail = []byte{0x00, 0x00, 0xff, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff}
2020

2121
type deflaterPool struct {
@@ -24,8 +24,8 @@ type deflaterPool struct {
2424
pool []*deflater
2525
}
2626

27-
// initialize 初始化deflaterPool
28-
// initialize the deflaterPool
27+
// 初始化deflaterPool
28+
// Initialize the deflaterPool
2929
func (c *deflaterPool) initialize(options PermessageDeflate, limit int) *deflaterPool {
3030
c.num = uint64(options.PoolSize)
3131
for i := uint64(0); i < c.num; i++ {
@@ -35,7 +35,7 @@ func (c *deflaterPool) initialize(options PermessageDeflate, limit int) *deflate
3535
}
3636

3737
// Select 从deflaterPool中选择一个deflater对象
38-
// select a deflater object from the deflaterPool
38+
// Select a deflater object from the deflaterPool
3939
func (c *deflaterPool) Select() *deflater {
4040
var j = atomic.AddUint64(&c.serial, 1) & (c.num - 1)
4141
return c.pool[j]
@@ -51,8 +51,8 @@ type deflater struct {
5151
cpsWriter *flate.Writer
5252
}
5353

54-
// initialize 初始化deflater
55-
// initialize the deflater
54+
// 初始化deflater
55+
// Initialize the deflater
5656
func (c *deflater) initialize(isServer bool, options PermessageDeflate, limit int) *deflater {
5757
c.dpsReader = flate.NewReader(nil)
5858
c.dpsBuffer = bytes.NewBuffer(nil)
@@ -67,19 +67,19 @@ func (c *deflater) initialize(isServer bool, options PermessageDeflate, limit in
6767
return c
6868
}
6969

70-
// resetFR 重置deflate reader
71-
// reset the deflate reader
70+
// 重置deflate reader
71+
// Reset the deflate reader
7272
func (c *deflater) resetFR(r io.Reader, dict []byte) {
7373
resetter := c.dpsReader.(flate.Resetter)
7474
_ = resetter.Reset(r, dict) // must return a null pointer
75-
if c.dpsBuffer.Cap() > 256*1024 {
75+
if c.dpsBuffer.Cap() > int(bufferThreshold) {
7676
c.dpsBuffer = bytes.NewBuffer(nil)
7777
}
7878
c.dpsBuffer.Reset()
7979
}
8080

8181
// Decompress 解压
82-
// decompress data
82+
// Decompress data
8383
func (c *deflater) Decompress(src *bytes.Buffer, dict []byte) (*bytes.Buffer, error) {
8484
c.dpsLocker.Lock()
8585
defer c.dpsLocker.Unlock()
@@ -96,7 +96,7 @@ func (c *deflater) Decompress(src *bytes.Buffer, dict []byte) (*bytes.Buffer, er
9696
}
9797

9898
// Compress 压缩
99-
// compress data
99+
// Compress data
100100
func (c *deflater) Compress(src internal.Payload, dst *bytes.Buffer, dict []byte) error {
101101
c.cpsLocker.Lock()
102102
defer c.cpsLocker.Unlock()
@@ -117,16 +117,16 @@ func (c *deflater) Compress(src internal.Payload, dst *bytes.Buffer, dict []byte
117117
return nil
118118
}
119119

120-
// slideWindow 滑动窗口
121-
// sliding window
120+
// 滑动窗口
121+
// Sliding window
122122
type slideWindow struct {
123123
enabled bool
124124
dict []byte
125125
size int
126126
}
127127

128-
// initialize 初始化滑动窗口
129-
// initialize the sliding window
128+
// 初始化滑动窗口
129+
// Initialize the sliding window
130130
func (c *slideWindow) initialize(pool *internal.Pool[[]byte], windowBits int) *slideWindow {
131131
c.enabled = true
132132
c.size = internal.BinaryPow(windowBits)
@@ -139,7 +139,7 @@ func (c *slideWindow) initialize(pool *internal.Pool[[]byte], windowBits int) *s
139139
}
140140

141141
// Write 将数据写入滑动窗口
142-
// write data to the sliding window
142+
// Write data to the sliding window
143143
func (c *slideWindow) Write(p []byte) (int, error) {
144144
if !c.enabled {
145145
return 0, nil
@@ -169,8 +169,8 @@ func (c *slideWindow) Write(p []byte) (int, error) {
169169
return total, nil
170170
}
171171

172-
// genRequestHeader 生成请求头
173-
// generate request headers
172+
// 生成请求头
173+
// Generate request headers
174174
func (c *PermessageDeflate) genRequestHeader() string {
175175
var options = make([]string, 0, 5)
176176
options = append(options, internal.PermessageDeflate)
@@ -191,8 +191,8 @@ func (c *PermessageDeflate) genRequestHeader() string {
191191
return strings.Join(options, "; ")
192192
}
193193

194-
// genResponseHeader 生成响应头
195-
// generate response headers
194+
// 生成响应头
195+
// Generate response headers
196196
func (c *PermessageDeflate) genResponseHeader() string {
197197
var options = make([]string, 0, 5)
198198
options = append(options, internal.PermessageDeflate)
@@ -211,7 +211,7 @@ func (c *PermessageDeflate) genResponseHeader() string {
211211
return strings.Join(options, "; ")
212212
}
213213

214-
// permessageNegotiation 压缩拓展协商
214+
// 压缩拓展协商
215215
// Negotiation of compression parameters
216216
func permessageNegotiation(str string) PermessageDeflate {
217217
var options = PermessageDeflate{
@@ -250,7 +250,7 @@ func permessageNegotiation(str string) PermessageDeflate {
250250
return options
251251
}
252252

253-
// limitReader 限制从io.Reader中最多读取m个字节
253+
// 限制从io.Reader中最多读取m个字节
254254
// Limit reading up to m bytes from io.Reader
255255
func limitReader(r io.Reader, m int) io.Reader { return &limitedReader{R: r, M: m} }
256256

conn.go

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ import (
1313
"github.com/lxzan/gws/internal"
1414
)
1515

16-
// Conn 结构体表示一个 WebSocket 连接
17-
// Conn struct represents a WebSocket connection
16+
// Conn WebSocket连接
17+
// WebSocket connection
1818
type Conn struct {
1919
// 互斥锁,用于保护共享资源
2020
// Mutex to protect shared resources
@@ -26,7 +26,7 @@ type Conn struct {
2626

2727
// 用于存储错误的原子值
2828
// Atomic value for storing errors
29-
err atomic.Value
29+
ev atomic.Value
3030

3131
// 标识是否为服务器端
3232
// Indicates if this is a server-side connection
@@ -76,16 +76,16 @@ type Conn struct {
7676
// Deflater
7777
deflater *deflater
7878

79-
// 数据包发送窗口
80-
// Data packet send window
79+
// 解压字典滑动窗口
80+
// Decompressing dictionary sliding window
8181
dpsWindow slideWindow
8282

83-
// 数据包接收窗口
84-
// Data packet receive window
83+
// 压缩字典滑动窗口
84+
// Compressed dictionary sliding window
8585
cpsWindow slideWindow
8686

87-
// 每消息压缩
88-
// Per-message deflate
87+
// 压缩拓展配置
88+
// Compression extension configuration
8989
pd PermessageDeflate
9090
}
9191

@@ -105,7 +105,7 @@ func (c *Conn) ReadLoop() {
105105
}
106106
}
107107

108-
err, ok := c.err.Load().(error)
108+
err, ok := c.ev.Load().(error)
109109
c.handler.OnClose(c, internal.SelectValue(ok, err, errEmpty))
110110

111111
// 回收资源
@@ -185,7 +185,7 @@ func (c *Conn) isClosed() bool {
185185
// 关闭连接并存储错误信息
186186
// Closes the connection and stores the error information
187187
func (c *Conn) close(reason []byte, err error) {
188-
c.err.Store(err)
188+
c.ev.Store(err)
189189
_ = c.doWrite(OpcodeCloseConnection, internal.Bytes(reason))
190190
_ = c.conn.Close()
191191
}
@@ -310,9 +310,9 @@ func (c *Conn) NetConn() net.Conn {
310310
return c.conn
311311
}
312312

313-
// SetNoDelay
314-
// 控制操作系统是否应该延迟数据包传输以期望发送更少的数据包(Nagle 算法)。
315-
// 默认值是 true(无延迟),这意味着数据在 Write 之后尽快发送
313+
// SetNoDelay 设置无延迟
314+
// 控制操作系统是否应该延迟数据包传输以期望发送更少的数据包(Nagle算法).
315+
// 默认值是 true(无延迟),这意味着数据在 Write 之后尽快发送.
316316
// Controls whether the operating system should delay packet transmission in hopes of sending fewer packets (Nagle's algorithm).
317317
// The default is true (no delay), meaning that data is sent as soon as possible after a Write.
318318
func (c *Conn) SetNoDelay(noDelay bool) error {

init.go

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,19 @@ package gws
33
import "github.com/lxzan/gws/internal"
44

55
var (
6-
framePadding = frameHeader{} // 帧头填充物
7-
binaryPool = internal.NewBufferPool(128, 256*1024) // 内存池
8-
defaultLogger = new(stdLogger) // 默认日志工具
6+
framePadding = frameHeader{} // 帧头填充物
7+
defaultLogger = new(stdLogger) // 默认日志工具
8+
bufferThreshold = uint32(256 * 1024) // buffer阈值
9+
binaryPool = new(internal.BufferPool) // 内存池
910
)
11+
12+
func init() {
13+
SetBufferThreshold(bufferThreshold)
14+
}
15+
16+
// SetBufferThreshold 设置buffer阈值, x=pow(2,n), 超过x个字节的buffer不会被回收
17+
// Set the buffer threshold, x=pow(2,n), that buffers larger than x bytes are not reclaimed.
18+
func SetBufferThreshold(x uint32) {
19+
bufferThreshold = internal.ToBinaryNumber(x)
20+
binaryPool = internal.NewBufferPool(128, bufferThreshold)
21+
}

0 commit comments

Comments
 (0)