Skip to content

Commit 3dc044f

Browse files
authored
Merge pull request #106 from lxzan/note
Add Comments & SetBufferThreshold
2 parents 38b4bdf + f55a412 commit 3dc044f

File tree

19 files changed

+837
-208
lines changed

19 files changed

+837
-208
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: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,11 @@ import (
1515
"github.com/lxzan/gws/internal"
1616
)
1717

18+
// Dialer 拨号器接口
19+
// Dialer interface
1820
type Dialer interface {
21+
// Dial 连接到指定网络上的地址
22+
// Connects to the address on the named network
1923
Dial(network, addr string) (c net.Conn, err error)
2024
}
2125

@@ -26,8 +30,8 @@ type connector struct {
2630
secWebsocketKey string
2731
}
2832

29-
// NewClient 创建客户端
30-
// Create New client
33+
// NewClient 创建一个新的 WebSocket 客户端连接
34+
// Creates a new WebSocket client connection
3135
func NewClient(handler Event, option *ClientOption) (*Conn, *http.Response, error) {
3236
option = initClientOption(option)
3337
c := &connector{option: option, eventHandler: handler}
@@ -69,7 +73,7 @@ func NewClient(handler Event, option *ClientOption) (*Conn, *http.Response, erro
6973
}
7074

7175
// NewClientFromConn 通过外部连接创建客户端, 支持 TCP/KCP/Unix Domain Socket
72-
// Create New client via external connection, supports TCP/KCP/Unix Domain Socket.
76+
// Create new client via external connection, supports TCP/KCP/Unix Domain Socket.
7377
func NewClientFromConn(handler Event, option *ClientOption, conn net.Conn) (*Conn, *http.Response, error) {
7478
option = initClientOption(option)
7579
c := &connector{option: option, conn: conn, eventHandler: handler}
@@ -80,12 +84,15 @@ func NewClientFromConn(handler Event, option *ClientOption, conn net.Conn) (*Con
8084
return client, resp, err
8185
}
8286

87+
// 发送HTTP请求, 即WebSocket握手
88+
// Sends an http request, i.e., websocket handshake
8389
func (c *connector) request() (*http.Response, *bufio.Reader, error) {
8490
_ = c.conn.SetDeadline(time.Now().Add(c.option.HandshakeTimeout))
8591
ctx, cancel := context.WithTimeout(context.Background(), c.option.HandshakeTimeout)
8692
defer cancel()
8793

88-
// 构建请求
94+
// 构建HTTP请求
95+
// building a http request
8996
r, err := http.NewRequestWithContext(ctx, http.MethodGet, c.option.Addr, nil)
9097
if err != nil {
9198
return nil, nil, err
@@ -109,10 +116,12 @@ func (c *connector) request() (*http.Response, *bufio.Reader, error) {
109116

110117
var ch = make(chan error)
111118

112-
// 发送请求
119+
// 发送http请求
120+
// send http request
113121
go func() { ch <- r.Write(c.conn) }()
114122

115123
// 同步等待请求是否发送成功
124+
// Synchronized waiting for the request to be sent successfully
116125
select {
117126
case err = <-ch:
118127
case <-ctx.Done():
@@ -123,11 +132,14 @@ func (c *connector) request() (*http.Response, *bufio.Reader, error) {
123132
}
124133

125134
// 读取响应结果
135+
// Read the response result
126136
br := bufio.NewReaderSize(c.conn, c.option.ReadBufferSize)
127137
resp, err := http.ReadResponse(br, r)
128138
return resp, br, err
129139
}
130140

141+
// 获取压缩拓展结果
142+
// Get compression expansion results
131143
func (c *connector) getPermessageDeflate(extensions string) PermessageDeflate {
132144
serverPD := permessageNegotiation(extensions)
133145
clientPD := c.option.PermessageDeflate
@@ -145,6 +157,8 @@ func (c *connector) getPermessageDeflate(extensions string) PermessageDeflate {
145157
return pd
146158
}
147159

160+
// 执行 WebSocket 握手操作
161+
// Performs the WebSocket handshake operation
148162
func (c *connector) handshake() (*Conn, *http.Response, error) {
149163
resp, br, err := c.request()
150164
if err != nil {
@@ -188,6 +202,8 @@ func (c *connector) handshake() (*Conn, *http.Response, error) {
188202
return socket, resp, c.conn.SetDeadline(time.Time{})
189203
}
190204

205+
// 从响应中获取子协议
206+
// Retrieves the subprotocol from the response
191207
func (c *connector) getSubProtocol(resp *http.Response) (string, error) {
192208
a := internal.Split(c.option.RequestHeader.Get(internal.SecWebSocketProtocol.Key), ",")
193209
b := internal.Split(resp.Header.Get(internal.SecWebSocketProtocol.Key), ",")
@@ -198,6 +214,8 @@ func (c *connector) getSubProtocol(resp *http.Response) (string, error) {
198214
return subprotocol, nil
199215
}
200216

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

compress.go

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

17-
// FlateTail Add four bytes as specified in RFC
18-
// Add final block to squelch unexpected EOF error from flate reader.
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,6 +24,8 @@ type deflaterPool struct {
2424
pool []*deflater
2525
}
2626

27+
// 初始化deflaterPool
28+
// Initialize the deflaterPool
2729
func (c *deflaterPool) initialize(options PermessageDeflate, limit int) *deflaterPool {
2830
c.num = uint64(options.PoolSize)
2931
for i := uint64(0); i < c.num; i++ {
@@ -32,6 +34,8 @@ func (c *deflaterPool) initialize(options PermessageDeflate, limit int) *deflate
3234
return c
3335
}
3436

37+
// Select 从deflaterPool中选择一个deflater对象
38+
// Select a deflater object from the deflaterPool
3539
func (c *deflaterPool) Select() *deflater {
3640
var j = atomic.AddUint64(&c.serial, 1) & (c.num - 1)
3741
return c.pool[j]
@@ -47,6 +51,8 @@ type deflater struct {
4751
cpsWriter *flate.Writer
4852
}
4953

54+
// 初始化deflater
55+
// Initialize the deflater
5056
func (c *deflater) initialize(isServer bool, options PermessageDeflate, limit int) *deflater {
5157
c.dpsReader = flate.NewReader(nil)
5258
c.dpsBuffer = bytes.NewBuffer(nil)
@@ -61,16 +67,19 @@ func (c *deflater) initialize(isServer bool, options PermessageDeflate, limit in
6167
return c
6268
}
6369

70+
// 重置deflate reader
71+
// Reset the deflate reader
6472
func (c *deflater) resetFR(r io.Reader, dict []byte) {
6573
resetter := c.dpsReader.(flate.Resetter)
6674
_ = resetter.Reset(r, dict) // must return a null pointer
67-
if c.dpsBuffer.Cap() > 256*1024 {
75+
if c.dpsBuffer.Cap() > int(bufferThreshold) {
6876
c.dpsBuffer = bytes.NewBuffer(nil)
6977
}
7078
c.dpsBuffer.Reset()
7179
}
7280

7381
// Decompress 解压
82+
// Decompress data
7483
func (c *deflater) Decompress(src *bytes.Buffer, dict []byte) (*bytes.Buffer, error) {
7584
c.dpsLocker.Lock()
7685
defer c.dpsLocker.Unlock()
@@ -87,6 +96,7 @@ func (c *deflater) Decompress(src *bytes.Buffer, dict []byte) (*bytes.Buffer, er
8796
}
8897

8998
// Compress 压缩
99+
// Compress data
90100
func (c *deflater) Compress(src internal.Payload, dst *bytes.Buffer, dict []byte) error {
91101
c.cpsLocker.Lock()
92102
defer c.cpsLocker.Unlock()
@@ -107,12 +117,16 @@ func (c *deflater) Compress(src internal.Payload, dst *bytes.Buffer, dict []byte
107117
return nil
108118
}
109119

120+
// 滑动窗口
121+
// Sliding window
110122
type slideWindow struct {
111123
enabled bool
112124
dict []byte
113125
size int
114126
}
115127

128+
// 初始化滑动窗口
129+
// Initialize the sliding window
116130
func (c *slideWindow) initialize(pool *internal.Pool[[]byte], windowBits int) *slideWindow {
117131
c.enabled = true
118132
c.size = internal.BinaryPow(windowBits)
@@ -124,6 +138,8 @@ func (c *slideWindow) initialize(pool *internal.Pool[[]byte], windowBits int) *s
124138
return c
125139
}
126140

141+
// Write 将数据写入滑动窗口
142+
// Write data to the sliding window
127143
func (c *slideWindow) Write(p []byte) (int, error) {
128144
if !c.enabled {
129145
return 0, nil
@@ -153,6 +169,8 @@ func (c *slideWindow) Write(p []byte) (int, error) {
153169
return total, nil
154170
}
155171

172+
// 生成请求头
173+
// Generate request headers
156174
func (c *PermessageDeflate) genRequestHeader() string {
157175
var options = make([]string, 0, 5)
158176
options = append(options, internal.PermessageDeflate)
@@ -173,6 +191,8 @@ func (c *PermessageDeflate) genRequestHeader() string {
173191
return strings.Join(options, "; ")
174192
}
175193

194+
// 生成响应头
195+
// Generate response headers
176196
func (c *PermessageDeflate) genResponseHeader() string {
177197
var options = make([]string, 0, 5)
178198
options = append(options, internal.PermessageDeflate)
@@ -191,7 +211,8 @@ func (c *PermessageDeflate) genResponseHeader() string {
191211
return strings.Join(options, "; ")
192212
}
193213

194-
// 压缩拓展握手协商
214+
// 压缩拓展协商
215+
// Negotiation of compression parameters
195216
func permessageNegotiation(str string) PermessageDeflate {
196217
var options = PermessageDeflate{
197218
ServerContextTakeover: true,
@@ -229,7 +250,9 @@ func permessageNegotiation(str string) PermessageDeflate {
229250
return options
230251
}
231252

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

234257
type limitedReader struct {
235258
R io.Reader

0 commit comments

Comments
 (0)