diff --git a/LICENSE b/LICENSE index 2920b379..b09cd785 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,201 @@ -MIT License - -Copyright (c) 2022 道友请留步 - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Makefile b/Makefile index cf4599fa..db334a02 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ test: - go test -count 1 -timeout 30s -run ^Test ./... + go test ./... bench: go test -benchmem -run=^$$ -bench . github.com/lxzan/gws diff --git a/assets/performance-compress-disabled.png b/assets/performance-compress-disabled.png index 5a474af0..e7312deb 100644 Binary files a/assets/performance-compress-disabled.png and b/assets/performance-compress-disabled.png differ diff --git a/benchmark_test.go b/benchmark_test.go index 39c1e768..5c7fcc27 100644 --- a/benchmark_test.go +++ b/benchmark_test.go @@ -93,9 +93,11 @@ func BenchmarkConn_ReadMessage(b *testing.B) { var conn1 = &Conn{ isServer: false, conn: &benchConn{}, - pd: PermessageDeflate{Enabled: true}, + pd: upgrader.option.PermessageDeflate, config: config, + deflater: new(deflater), } + conn1.deflater.initialize(false, conn1.pd) var buf, _ = conn1.genFrame(OpcodeText, githubData, false) var reader = bytes.NewBuffer(buf.Bytes()) @@ -104,7 +106,7 @@ func BenchmarkConn_ReadMessage(b *testing.B) { conn: &benchConn{}, br: bufio.NewReader(reader), config: upgrader.option.getConfig(), - pd: PermessageDeflate{Enabled: true}, + pd: upgrader.option.PermessageDeflate, handler: upgrader.eventHandler, deflater: upgrader.deflaterPool.Select(), } diff --git a/client.go b/client.go index 85b2c919..55bfcd01 100644 --- a/client.go +++ b/client.go @@ -2,6 +2,7 @@ package gws import ( "bufio" + "context" "crypto/tls" "encoding/base64" "encoding/binary" @@ -22,7 +23,6 @@ type connector struct { option *ClientOption conn net.Conn eventHandler Event - resp *http.Response secWebsocketKey string } @@ -30,7 +30,7 @@ type connector struct { // Create New client func NewClient(handler Event, option *ClientOption) (*Conn, *http.Response, error) { option = initClientOption(option) - c := &connector{option: option, eventHandler: handler, resp: &http.Response{}} + c := &connector{option: option, eventHandler: handler} URL, err := url.Parse(option.Addr) if err != nil { return nil, nil, err @@ -72,7 +72,7 @@ func NewClient(handler Event, option *ClientOption) (*Conn, *http.Response, erro // Create New client via external connection, supports TCP/KCP/Unix Domain Socket. func NewClientFromConn(handler Event, option *ClientOption, conn net.Conn) (*Conn, *http.Response, error) { option = initClientOption(option) - c := &connector{option: option, conn: conn, eventHandler: handler, resp: &http.Response{}} + c := &connector{option: option, conn: conn, eventHandler: handler} client, resp, err := c.handshake() if err != nil { _ = c.conn.Close() @@ -80,12 +80,19 @@ func NewClientFromConn(handler Event, option *ClientOption, conn net.Conn) (*Con return client, resp, err } -func (c *connector) writeRequest() (*http.Request, error) { - r, err := http.NewRequest(http.MethodGet, c.option.Addr, nil) +func (c *connector) request() (*http.Response, *bufio.Reader, error) { + _ = c.conn.SetDeadline(time.Now().Add(c.option.HandshakeTimeout)) + ctx, cancel := context.WithTimeout(context.Background(), c.option.HandshakeTimeout) + defer cancel() + + // 构建请求 + r, err := http.NewRequestWithContext(ctx, http.MethodGet, c.option.Addr, nil) if err != nil { - return nil, err + return nil, nil, err + } + for k, v := range c.option.RequestHeader { + r.Header[k] = v } - r.Header = c.option.RequestHeader.Clone() r.Header.Set(internal.Connection.Key, internal.Connection.Val) r.Header.Set(internal.Upgrade.Key, internal.Upgrade.Val) r.Header.Set(internal.SecWebSocketVersion.Key, internal.SecWebSocketVersion.Val) @@ -99,7 +106,26 @@ func (c *connector) writeRequest() (*http.Request, error) { c.secWebsocketKey = base64.StdEncoding.EncodeToString(key[0:]) r.Header.Set(internal.SecWebSocketKey.Key, c.secWebsocketKey) } - return r, r.Write(c.conn) + + var ch = make(chan error) + + // 发送请求 + go func() { ch <- r.Write(c.conn) }() + + // 同步等待请求是否发送成功 + select { + case err = <-ch: + case <-ctx.Done(): + err = ctx.Err() + } + if err != nil { + return nil, nil, err + } + + // 读取响应结果 + br := bufio.NewReaderSize(c.conn, c.option.ReadBufferSize) + resp, err := http.ReadResponse(br, r) + return resp, br, err } func (c *connector) getPermessageDeflate(extensions string) PermessageDeflate { @@ -118,34 +144,19 @@ func (c *connector) getPermessageDeflate(extensions string) PermessageDeflate { } func (c *connector) handshake() (*Conn, *http.Response, error) { - if err := c.conn.SetDeadline(time.Now().Add(c.option.HandshakeTimeout)); err != nil { - return nil, c.resp, err - } - br := bufio.NewReaderSize(c.conn, c.option.ReadBufferSize) - request, err := c.writeRequest() + resp, br, err := c.request() if err != nil { - return nil, c.resp, err - } - var ch = make(chan error) - go func() { - c.resp, err = http.ReadResponse(br, request) - ch <- err - }() - if err := <-ch; err != nil { - return nil, c.resp, err - } - if err := c.checkHeaders(); err != nil { - return nil, c.resp, err + return nil, resp, err } - if err := c.conn.SetDeadline(time.Time{}); err != nil { - return nil, c.resp, err + if err = c.checkHeaders(resp); err != nil { + return nil, resp, err } - subprotocol, err := c.getSubProtocol() + subprotocol, err := c.getSubProtocol(resp) if err != nil { - return nil, c.resp, err + return nil, resp, err } - var extensions = c.resp.Header.Get(internal.SecWebSocketExtensions.Key) + var extensions = resp.Header.Get(internal.SecWebSocketExtensions.Key) var pd = c.getPermessageDeflate(extensions) socket := &Conn{ ss: c.option.NewSession(), @@ -172,12 +183,12 @@ func (c *connector) handshake() (*Conn, *http.Response, error) { socket.cpsWindow.initialize(pd.ClientMaxWindowBits) } } - return socket, c.resp, nil + return socket, resp, c.conn.SetDeadline(time.Time{}) } -func (c *connector) getSubProtocol() (string, error) { +func (c *connector) getSubProtocol(resp *http.Response) (string, error) { a := internal.Split(c.option.RequestHeader.Get(internal.SecWebSocketProtocol.Key), ",") - b := internal.Split(c.resp.Header.Get(internal.SecWebSocketProtocol.Key), ",") + b := internal.Split(resp.Header.Get(internal.SecWebSocketProtocol.Key), ",") subprotocol := internal.GetIntersectionElem(a, b) if len(a) > 0 && subprotocol == "" { return "", ErrSubprotocolNegotiation @@ -185,17 +196,17 @@ func (c *connector) getSubProtocol() (string, error) { return subprotocol, nil } -func (c *connector) checkHeaders() error { - if c.resp.StatusCode != http.StatusSwitchingProtocols { +func (c *connector) checkHeaders(resp *http.Response) error { + if resp.StatusCode != http.StatusSwitchingProtocols { return ErrHandshake } - if !internal.HttpHeaderContains(c.resp.Header.Get(internal.Connection.Key), internal.Connection.Val) { + if !internal.HttpHeaderContains(resp.Header.Get(internal.Connection.Key), internal.Connection.Val) { return ErrHandshake } - if !strings.EqualFold(c.resp.Header.Get(internal.Upgrade.Key), internal.Upgrade.Val) { + if !strings.EqualFold(resp.Header.Get(internal.Upgrade.Key), internal.Upgrade.Val) { return ErrHandshake } - if c.resp.Header.Get(internal.SecWebSocketAccept.Key) != internal.ComputeAcceptKey(c.secWebsocketKey) { + if resp.Header.Get(internal.SecWebSocketAccept.Key) != internal.ComputeAcceptKey(c.secWebsocketKey) { return ErrHandshake } return nil diff --git a/client_test.go b/client_test.go index d56c2732..c03437ca 100644 --- a/client_test.go +++ b/client_test.go @@ -86,7 +86,6 @@ func TestClientHandshake(t *testing.T) { option: option, conn: cli, eventHandler: new(BuiltinEventHandler), - resp: &http.Response{Header: http.Header{}}, secWebsocketKey: "1fTfP/qALD+eAWcU80P0bg==", } @@ -120,7 +119,6 @@ func TestClientHandshakeFail(t *testing.T) { conn: cli, secWebsocketKey: "1fTfP/qALD+eAWcU80P0bg==", eventHandler: new(BuiltinEventHandler), - resp: &http.Response{Header: http.Header{}}, } go func() { @@ -148,7 +146,6 @@ func TestClientHandshakeFail(t *testing.T) { conn: cli, secWebsocketKey: "1fTfP/qALD+eAWcU80P0bg==", eventHandler: new(BuiltinEventHandler), - resp: &http.Response{Header: http.Header{}}, } go func() { @@ -175,7 +172,6 @@ func TestClientHandshakeFail(t *testing.T) { conn: cli, secWebsocketKey: "1fTfP/qALD+eAWcU80P0bg==", eventHandler: new(BuiltinEventHandler), - resp: &http.Response{Header: http.Header{}}, } go func() { @@ -203,7 +199,6 @@ func TestClientHandshakeFail(t *testing.T) { conn: cli, secWebsocketKey: "1fTfP/qALD+eAWcU80P0bg==", eventHandler: new(BuiltinEventHandler), - resp: &http.Response{Header: http.Header{}}, } go func() { @@ -231,7 +226,6 @@ func TestClientHandshakeFail(t *testing.T) { conn: cli, secWebsocketKey: "1fTfP/qALD+eAWcU80P0bg==", eventHandler: new(BuiltinEventHandler), - resp: &http.Response{Header: http.Header{}}, } go func() { @@ -259,7 +253,6 @@ func TestClientHandshakeFail(t *testing.T) { conn: cli, secWebsocketKey: "1fTfP/qALD+eAWcU80P0bg==", eventHandler: new(BuiltinEventHandler), - resp: &http.Response{Header: http.Header{}}, } go func() { @@ -388,8 +381,29 @@ func TestNewClientWSS(t *testing.T) { func TestNewClient_WriteRequest(t *testing.T) { t.Run("", func(t *testing.T) { - c := connector{option: &ClientOption{Addr: "ws://127.0.0.1/a=%"}} - _, err := c.writeRequest() + srv, conn := net.Pipe() + go func() { + for { + var p = make([]byte, 1024) + srv.Read(p) + time.Sleep(time.Second) + } + }() + c := connector{conn: conn, option: &ClientOption{ + Addr: "ws://127.0.0.1/a=%", + HandshakeTimeout: 100 * time.Millisecond, + }} + _, _, err := c.request() + assert.Error(t, err) + }) + + t.Run("", func(t *testing.T) { + _, conn := net.Pipe() + c := connector{conn: conn, option: &ClientOption{ + Addr: "ws://127.0.0.1:8080/", + HandshakeTimeout: 100 * time.Millisecond, + }} + _, _, err := c.request() assert.Error(t, err) }) diff --git a/compress_test.go b/compress_test.go index aedba3ff..c9499d5a 100644 --- a/compress_test.go +++ b/compress_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + "github.com/lxzan/gws/internal" + "github.com/stretchr/testify/assert" ) @@ -129,4 +131,32 @@ func TestPermessageNegotiation(t *testing.T) { assert.Equal(t, client.pd.ClientContextTakeover, false) assert.NoError(t, err) }) + + t.Run("ok 4", func(t *testing.T) { + var addr = ":" + nextPort() + var serverHandler = &webSocketMocker{} + serverHandler.onOpen = func(socket *Conn) { + socket.WriteMessage(OpcodeText, internal.AlphabetNumeric.Generate(1024)) + } + var server = NewServer(serverHandler, &ServerOption{PermessageDeflate: PermessageDeflate{ + Enabled: true, + ServerContextTakeover: true, + ClientContextTakeover: true, + ServerMaxWindowBits: 10, + ClientMaxWindowBits: 10, + }}) + go server.Run(addr) + + time.Sleep(100 * time.Millisecond) + client, _, err := NewClient(new(BuiltinEventHandler), &ClientOption{ + Addr: "ws://localhost" + addr, + PermessageDeflate: PermessageDeflate{ + Enabled: true, + ServerContextTakeover: true, + ClientContextTakeover: true, + }, + }) + assert.NoError(t, err) + client.WriteMessage(OpcodeText, internal.AlphabetNumeric.Generate(1024)) + }) } diff --git a/conn.go b/conn.go index de6b5a28..9303bd1a 100644 --- a/conn.go +++ b/conn.go @@ -58,29 +58,24 @@ func (c *Conn) ReadLoop() { } func (c *Conn) getCpsDict(isBroadcast bool) []byte { + // 广播模式必须保证每一帧都是相同的内容, 所以不使用上下文接管优化压缩率 if isBroadcast { - return nil // 广播模式不使用上下文接管 - } - if c.isServer { - if c.pd.ServerContextTakeover { - return c.cpsWindow.dict - } return nil } - if c.pd.ClientContextTakeover { + if c.isServer && c.pd.ServerContextTakeover { + return c.cpsWindow.dict + } + if !c.isServer && c.pd.ClientContextTakeover { return c.cpsWindow.dict } return nil } func (c *Conn) getDpsDict() []byte { - if c.isServer { - if c.pd.ClientContextTakeover { - return c.dpsWindow.dict - } - return nil + if c.isServer && c.pd.ClientContextTakeover { + return c.dpsWindow.dict } - if c.pd.ServerContextTakeover { + if !c.isServer && c.pd.ServerContextTakeover { return c.dpsWindow.dict } return nil diff --git a/conn_test.go b/conn_test.go index a33a0b34..680181b2 100644 --- a/conn_test.go +++ b/conn_test.go @@ -19,6 +19,7 @@ type webSocketMocker struct { onPing func(socket *Conn, payload []byte) onPong func(socket *Conn, payload []byte) onClose func(socket *Conn, err error) + onOpen func(socket *Conn) } func (c *webSocketMocker) reset(socket *Conn, reader *bytes.Buffer, writer *bytes.Buffer) { @@ -29,6 +30,9 @@ func (c *webSocketMocker) reset(socket *Conn, reader *bytes.Buffer, writer *byte } func (c *webSocketMocker) OnOpen(socket *Conn) { + if c.onOpen != nil { + c.onOpen(socket) + } } func (c *webSocketMocker) OnClose(socket *Conn, err error) { diff --git a/examples/push/main.go b/examples/push/main.go index 740eb776..1d23c05f 100644 --- a/examples/push/main.go +++ b/examples/push/main.go @@ -1,7 +1,9 @@ package main import ( + "bufio" "log" + "net" "net/http" "github.com/lxzan/gws" @@ -10,7 +12,12 @@ import ( func main() { var app = gws.NewServer(new(Handler), nil) - app.OnRequest = func(socket *gws.Conn, request *http.Request) { + app.OnRequest = func(conn net.Conn, br *bufio.Reader, r *http.Request) { + socket, err := app.GetUpgrader().UpgradeFromConn(conn, br, r) + if err != nil { + log.Print(err.Error()) + return + } var channel = make(chan []byte, 8) var closer = make(chan struct{}) socket.Session().Store("channel", channel) diff --git a/go.mod b/go.mod index 7fbc25ee..c8c941a6 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/dolthub/maphash v0.1.0 - github.com/klauspost/compress v1.17.4 + github.com/klauspost/compress v1.17.5-0.20240119100516-32312d57f3c7 github.com/stretchr/testify v1.8.4 ) diff --git a/go.sum b/go.sum index f27f4bc0..bf084870 100644 --- a/go.sum +++ b/go.sum @@ -2,8 +2,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dolthub/maphash v0.1.0 h1:bsQ7JsF4FkkWyrP3oCnFJgrCUAFbFf3kOl4L/QxPDyQ= github.com/dolthub/maphash v0.1.0/go.mod h1:gkg4Ch4CdCDu5h6PMriVLawB7koZ+5ijb9puGMV50a4= -github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4= -github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM= +github.com/klauspost/compress v1.17.5-0.20240119100516-32312d57f3c7 h1:cBVUjnVhEblq1CXwboJtC3F1lQYutr/4sVsnhLUAgiE= +github.com/klauspost/compress v1.17.5-0.20240119100516-32312d57f3c7/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= diff --git a/internal/deque.go b/internal/deque.go index b852b1e9..5add7562 100644 --- a/internal/deque.go +++ b/internal/deque.go @@ -302,14 +302,9 @@ func (c *Stack[T]) Push(v T) { } // Pop 弹出元素 -func (c *Stack[T]) Pop() (value T) { +func (c *Stack[T]) Pop() T { n := c.Len() - switch n { - case 0: - return - default: - value = (*c)[n-1] - *c = (*c)[:n-1] - return - } + value := (*c)[n-1] + *c = (*c)[:n-1] + return value } diff --git a/upgrader.go b/upgrader.go index 5e419500..972a26f6 100644 --- a/upgrader.go +++ b/upgrader.go @@ -7,6 +7,7 @@ import ( "errors" "net" "net/http" + "strconv" "strings" "time" @@ -80,28 +81,14 @@ func NewUpgrader(eventHandler Event, option *ServerOption) *Upgrader { u := &Upgrader{ option: initServerOption(option), eventHandler: eventHandler, + deflaterPool: new(deflaterPool), } if u.option.PermessageDeflate.Enabled { - u.deflaterPool = new(deflaterPool).initialize(u.option.PermessageDeflate) + u.deflaterPool.initialize(u.option.PermessageDeflate) } return u } -// Upgrade http upgrade to websocket protocol -func (c *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request) (*Conn, error) { - netConn, br, err := c.hijack(w) - if err != nil { - return nil, err - } - - socket, err := c.doUpgrade(r, netConn, br) - if err != nil { - _ = netConn.Close() - return nil, err - } - return socket, err -} - // 为了节省内存, 不复用hijack返回的bufio.ReadWriter func (c *Upgrader) hijack(w http.ResponseWriter) (net.Conn, *bufio.Reader, error) { hj, ok := w.(http.Hijacker) @@ -132,7 +119,42 @@ func (c *Upgrader) getPermessageDeflate(extensions string) PermessageDeflate { } } -func (c *Upgrader) doUpgrade(r *http.Request, netConn net.Conn, br *bufio.Reader) (*Conn, error) { +// Upgrade +// 升级HTTP到WebSocket协议 +// http upgrade to websocket protocol +func (c *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request) (*Conn, error) { + netConn, br, err := c.hijack(w) + if err != nil { + return nil, err + } + return c.UpgradeFromConn(netConn, br, r) +} + +// UpgradeFromConn 从连接(TCP/KCP/Unix Domain Socket...)升级到WebSocket协议 +func (c *Upgrader) UpgradeFromConn(conn net.Conn, br *bufio.Reader, r *http.Request) (*Conn, error) { + socket, err := c.doUpgradeFromConn(conn, br, r) + if err != nil { + _ = c.writeErr(conn, err) + _ = conn.Close() + } + return socket, err +} + +func (c *Upgrader) writeErr(conn net.Conn, err error) error { + var str = err.Error() + var buf = binaryPool.Get(256) + buf.WriteString("HTTP/1.1 400 Bad Request\r\n") + buf.WriteString("Date: " + time.Now().Format(time.RFC1123) + "\r\n") + buf.WriteString("Content-Length: " + strconv.Itoa(len(str)) + "\r\n") + buf.WriteString("Content-Type: text/plain; charset=utf-8\r\n") + buf.WriteString("\r\n") + buf.WriteString(str) + _, result := buf.WriteTo(conn) + binaryPool.Put(buf) + return result +} + +func (c *Upgrader) doUpgradeFromConn(netConn net.Conn, br *bufio.Reader, r *http.Request) (*Conn, error) { var session = c.option.NewSession() if !c.option.Authorize(r, session) { return nil, ErrUnauthorized @@ -202,12 +224,11 @@ type Server struct { upgrader *Upgrader option *ServerOption - // OnError 接收握手过程中产生的错误回调 - // Receive error callbacks generated during the handshake + // OnError OnError func(conn net.Conn, err error) // OnRequest - OnRequest func(socket *Conn, request *http.Request) + OnRequest func(conn net.Conn, br *bufio.Reader, r *http.Request) } // NewServer 创建websocket服务器 @@ -216,10 +237,19 @@ func NewServer(eventHandler Event, option *ServerOption) *Server { var c = &Server{upgrader: NewUpgrader(eventHandler, option)} c.option = c.upgrader.option c.OnError = func(conn net.Conn, err error) { c.option.Logger.Error("gws: " + err.Error()) } - c.OnRequest = func(socket *Conn, request *http.Request) { socket.ReadLoop() } + c.OnRequest = func(conn net.Conn, br *bufio.Reader, r *http.Request) { + socket, err := c.GetUpgrader().UpgradeFromConn(conn, br, r) + if err != nil { + c.OnError(conn, err) + } else { + socket.ReadLoop() + } + } return c } +func (c *Server) GetUpgrader() *Upgrader { return c.upgrader } + // Run 运行. 可以被多次调用, 监听不同的地址. // It can be called multiple times, listening to different addresses. func (c *Server) Run(addr string) error { @@ -267,20 +297,11 @@ func (c *Server) RunListener(listener net.Listener) error { go func(conn net.Conn) { br := c.option.config.readerPool.Get() br.Reset(conn) - r, err := http.ReadRequest(br) - if err != nil { - c.OnError(conn, err) - _ = conn.Close() - return - } - - socket, err := c.upgrader.doUpgrade(r, conn, br) - if err != nil { + if r, err := http.ReadRequest(br); err != nil { c.OnError(conn, err) - _ = conn.Close() - return + } else { + c.OnRequest(conn, br, r) } - c.OnRequest(socket, r) }(netConn) } } diff --git a/writer_test.go b/writer_test.go index 1feac625..8d8a3c68 100644 --- a/writer_test.go +++ b/writer_test.go @@ -1,6 +1,7 @@ package gws import ( + "bufio" "bytes" "io" "net" @@ -176,11 +177,14 @@ func TestNewBroadcaster(t *testing.T) { PermessageDeflate: PermessageDeflate{Enabled: true}, }) - app.OnRequest = func(socket *Conn, request *http.Request) { + app.OnRequest = func(netConn net.Conn, br *bufio.Reader, r *http.Request) { + socket, err := app.GetUpgrader().UpgradeFromConn(netConn, br, r) + if err != nil { + return + } handler.sockets.Store(socket, struct{}{}) socket.ReadLoop() } - go func() { if err := app.Run(addr); err != nil { as.NoError(err) @@ -228,7 +232,11 @@ func TestNewBroadcaster(t *testing.T) { }, }) - app.OnRequest = func(socket *Conn, request *http.Request) { + app.OnRequest = func(netConn net.Conn, br *bufio.Reader, r *http.Request) { + socket, err := app.GetUpgrader().UpgradeFromConn(netConn, br, r) + if err != nil { + return + } name, _ := socket.Session().Load("name") as.Equal(2, name) handler.sockets.Store(socket, struct{}{})