├── .idea ├── microSocket.iml ├── misc.xml ├── modules.xml ├── vcs.xml └── workspace.xml ├── LICENSE ├── README.md ├── cache └── cache.go ├── example ├── cli.go └── ser.go ├── hComSocket.go ├── hWebSocket.go ├── routers.go ├── server.go ├── session.go └── util ├── StringMap.go ├── chanMap.go ├── file.go └── safeMap.go /.idea/microSocket.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/workspace.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 13 | 14 | 24 | 25 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 234 | 235 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 359 | 360 | 361 | 362 | 363 | 364 | -------------------------------------------------------------------------------- /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 | # microSocket 2 | 这是一款十分适合学习的go语言socket框架 3 | socket 和websocket 一键切换 业务代码完全不用改 4 | 5 | 6 | 能够非常简单就实现一个服务端 7 | 8 | ```go 9 | package main 10 | 11 | import ( 12 | "log" 13 | msf "microSocket" 14 | "net" 15 | ) 16 | 17 | var ser = msf.NewMsf(&msf.CommSocket{}) 18 | 19 | //框架事件 20 | //---------------------------------------------------------------------------------------------------------------------- 21 | type event struct { 22 | } 23 | 24 | //客户端握手成功事件 25 | func (this event) OnHandel(fd uint32, conn net.Conn) bool { 26 | log.Println(fd, "链接成功类") 27 | return true 28 | } 29 | 30 | //断开连接事件 31 | func (this event) OnClose(fd uint32) { 32 | log.Println(fd, "链接断开类") 33 | } 34 | 35 | //接收到消息事件 36 | func (this event) OnMessage(fd uint32, msg map[string]string) bool { 37 | log.Println("这个是接受消息事件",msg) 38 | return true 39 | } 40 | //---------------------------------------------------------------------------------------------------------------------- 41 | //框架业务逻辑 42 | type Test struct { 43 | } 44 | 45 | func (this Test) Default(fd uint32,data map[string]string) bool { 46 | log.Println("default") 47 | return true 48 | } 49 | 50 | func (this Test) BeforeRequest(fd uint32,data map[string]string) bool { 51 | log.Println("before") 52 | return true 53 | } 54 | 55 | func (this Test) AfterRequest(fd uint32,data map[string]string) bool{ 56 | log.Println("after") 57 | return true 58 | } 59 | 60 | func (this Test) Hello(fd uint32,data map[string]string) bool { 61 | log.Println("收到消息了") 62 | log.Println(data) 63 | ser.SessionMaster.WriteByid(fd,[]byte("hehehehehehehehe")) 64 | return true 65 | } 66 | 67 | 68 | //---------------------------------------------------------------------------------------------------------------------- 69 | func main() { 70 | log.SetFlags(log.Lshortfile | log.LstdFlags | log.Llongfile) 71 | ser.EventPool.RegisterEvent(&event{}) 72 | ser.EventPool.RegisterStructFun("test", &Test{}) 73 | ser.Listening(":8565") 74 | } 75 | 76 | 77 | 78 | ``` 79 | 客户端连接成功后发送"module:test|action:Hello"就能 触发相应模块事件 80 | 81 | 我也对该框架做了源码分析 [传送](https://www.jianshu.com/p/49974703cf3e) -------------------------------------------------------------------------------- /cache/cache.go: -------------------------------------------------------------------------------- 1 | package cache 2 | 3 | import ( 4 | "log" 5 | "microSocket/util" 6 | "sync" 7 | "time" 8 | ) 9 | 10 | var ( 11 | fileCache sync.Map 12 | memoryCache sync.Map 13 | fileLock sync.Mutex 14 | ) 15 | 16 | //缓存 数据 17 | func SaveCache(key, value string, isFile bool) bool { 18 | if isFile { 19 | _, ok := fileCache.LoadOrStore(key, value) 20 | return ok 21 | } else { 22 | _, ok := memoryCache.LoadOrStore(key, value) 23 | return ok 24 | } 25 | 26 | } 27 | 28 | //获取数据 29 | func GetCache(key string, isFile bool) string { 30 | if isFile { 31 | v, ok := fileCache.Load(key) 32 | if ok { 33 | return v.(string) 34 | } 35 | } else { 36 | v, ok := memoryCache.Load(key) 37 | if ok { 38 | return v.(string) 39 | } 40 | } 41 | return "'" 42 | } 43 | 44 | //删除数据 45 | func DeleteCache(key string, isFile bool) { 46 | if isFile { 47 | fileCache.Delete(key) 48 | } else { 49 | memoryCache.Delete(key) 50 | } 51 | } 52 | 53 | //每隔一段时间缓存一次到文件里面 54 | func saveFile() { 55 | saveMap := make(map[string]string) 56 | 57 | fileCache.Range(func(key, value interface{}) bool { 58 | saveMap[key.(string)] = value.(string) 59 | return true 60 | }) 61 | 62 | saveStr := util.Map2String(saveMap) 63 | 64 | fileLock.Lock() 65 | defer fileLock.Unlock() 66 | log.Println(saveStr) 67 | util.WriteFile("./tmp.txt", saveStr) 68 | } 69 | 70 | //在此模块一开始运行的时候加载缓存文件 71 | func loadFile() { 72 | fileLock.Lock() 73 | defer fileLock.Unlock() 74 | 75 | fileStr, _ := util.ReadFile("./tmp.txt") 76 | loadMap := util.String2Map(fileStr) 77 | 78 | for i, v := range loadMap { 79 | fileCache.LoadOrStore(i, v) 80 | } 81 | } 82 | 83 | func init() { 84 | loadFile() 85 | 86 | go func() { 87 | for { 88 | time.Sleep(time.Second) 89 | saveFile() 90 | } 91 | }() 92 | } 93 | -------------------------------------------------------------------------------- /example/cli.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ms "microSocket" 6 | "microSocket/util" 7 | "net" 8 | ) 9 | 10 | func main() { 11 | conn, err := net.Dial("tcp", "127.0.0.1:8565") 12 | if err != nil { 13 | return 14 | } 15 | defer conn.Close() 16 | 17 | data := make(map[string]string) 18 | data["module"] = "test" 19 | data["method"] = "Hello" 20 | data["name"] = "jd" 21 | //把map转化为string 22 | a := []byte(util.Map2String(data)) 23 | 24 | //把string打包 25 | sock := &ms.CommSocket{} 26 | b := sock.Pack(a) 27 | 28 | //发送数据 29 | conn.Write(b) 30 | 31 | res := make([]byte, 20) 32 | conn.Read(res) 33 | fmt.Println(string(res)) 34 | } 35 | -------------------------------------------------------------------------------- /example/ser.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | msf "microSocket" 6 | "net" 7 | ) 8 | 9 | var ser = msf.NewMsf(&msf.CommSocket{}) 10 | 11 | //框架事件 12 | //---------------------------------------------------------------------------------------------------------------------- 13 | type event struct { 14 | } 15 | 16 | //客户端握手成功事件 17 | func (this event) OnHandel(fd uint32, conn net.Conn) bool { 18 | log.Println(fd, "链接成功类") 19 | return true 20 | } 21 | 22 | //断开连接事件 23 | func (this event) OnClose(fd uint32) { 24 | log.Println(fd, "链接断开类") 25 | } 26 | 27 | //接收到消息事件 28 | func (this event) OnMessage(fd uint32, msg map[string]string) bool { 29 | log.Println("这个是接受消息事件",msg) 30 | return true 31 | } 32 | //---------------------------------------------------------------------------------------------------------------------- 33 | //框架业务逻辑 34 | type Test struct { 35 | } 36 | 37 | func (this Test) Default(fd uint32,data map[string]string) bool { 38 | log.Println("default") 39 | return true 40 | } 41 | 42 | func (this Test) BeforeRequest(fd uint32,data map[string]string) bool { 43 | log.Println("before") 44 | return true 45 | } 46 | 47 | func (this Test) AfterRequest(fd uint32,data map[string]string) bool{ 48 | log.Println("after") 49 | return true 50 | } 51 | 52 | func (this Test) Hello(fd uint32,data map[string]string) bool { 53 | log.Println("收到消息了") 54 | log.Println(data) 55 | ser.SessionMaster.WriteByid(fd,[]byte("hehehehehehehehe")) 56 | return true 57 | } 58 | 59 | 60 | //---------------------------------------------------------------------------------------------------------------------- 61 | func main() { 62 | log.SetFlags(log.Lshortfile | log.LstdFlags | log.Llongfile) 63 | ser.EventPool.RegisterEvent(&event{}) 64 | ser.EventPool.RegisterStructFun("test", &Test{}) 65 | ser.Listening(":8565") 66 | } 67 | -------------------------------------------------------------------------------- /hComSocket.go: -------------------------------------------------------------------------------- 1 | package microSocket 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "errors" 7 | "log" 8 | "microSocket/util" 9 | ) 10 | 11 | const ( 12 | CONSTHEADER = "Header" 13 | CONSTHEADERLENGTH = 6 14 | CONSTMLENGTH = 4 15 | ) 16 | 17 | type CommSocket struct { 18 | } 19 | 20 | func (this *CommSocket) ConnHandle(msf *Msf, sess *Session) { 21 | defer func() { 22 | msf.SessionMaster.DelSessionById(sess.Id) 23 | //调用断开链接事件 24 | msf.EventPool.OnClose(sess.Id) 25 | }() 26 | var errs error 27 | tempBuff := make([]byte, 0) 28 | readBuff := make([]byte, 14) 29 | data := make([]byte, 20) 30 | for { 31 | n, err := sess.Con.Read(readBuff) 32 | //更新接收时间 33 | sess.updateTime() 34 | if err != nil { 35 | return 36 | } 37 | tempBuff = append(tempBuff, readBuff[:n]...) 38 | tempBuff, data, errs = this.Depack(tempBuff) 39 | if errs != nil { 40 | log.Println(errs) 41 | return 42 | } 43 | 44 | if len(data) == 0 { 45 | continue 46 | } 47 | //把请求的到数据转化为map 48 | requestData := util.String2Map(string(data)) 49 | if msf.Hook(sess.Id,requestData) == false { 50 | return 51 | } 52 | } 53 | } 54 | 55 | func (this *CommSocket) Pack(message []byte) []byte { 56 | return append(append([]byte(CONSTHEADER), this.IntToBytes(len(message))...), message...) 57 | } 58 | 59 | //解包 60 | func (this *CommSocket) Depack(buff []byte) ([]byte, []byte, error) { 61 | length := len(buff) 62 | //如果包长小于header 就直接返回 因为接收的数据不完整 63 | if length < CONSTHEADERLENGTH+CONSTMLENGTH { 64 | return buff, nil, nil 65 | } 66 | 67 | //如果header不是 指定的header 说明此数据已经被污染 直接返回错误 68 | if string(buff[:CONSTHEADERLENGTH]) != CONSTHEADER { 69 | return []byte{}, nil, errors.New("header is not safe") 70 | } 71 | 72 | msgLength := this.BytesToInt(buff[CONSTHEADERLENGTH : CONSTHEADERLENGTH+CONSTMLENGTH]) 73 | if length < CONSTHEADERLENGTH+CONSTMLENGTH+msgLength { 74 | return buff, nil, nil 75 | } 76 | 77 | data := buff[CONSTHEADERLENGTH+CONSTMLENGTH : CONSTHEADERLENGTH+CONSTMLENGTH+msgLength] 78 | buffs := buff[CONSTHEADERLENGTH+CONSTMLENGTH+msgLength:] 79 | return buffs, data, nil 80 | } 81 | 82 | func (this *CommSocket) IntToBytes(n int) []byte { 83 | x := int32(n) 84 | bytesBuffer := bytes.NewBuffer([]byte{}) 85 | binary.Write(bytesBuffer, binary.BigEndian, x) 86 | return bytesBuffer.Bytes() 87 | } 88 | 89 | func (this *CommSocket) BytesToInt(b []byte) int { 90 | bytesBuffer := bytes.NewBuffer(b) 91 | var x int32 92 | binary.Read(bytesBuffer, binary.BigEndian, &x) 93 | return int(x) 94 | } 95 | -------------------------------------------------------------------------------- /hWebSocket.go: -------------------------------------------------------------------------------- 1 | package microSocket 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "crypto/sha1" 7 | "encoding/base64" 8 | "encoding/binary" 9 | "io" 10 | "log" 11 | "microSocket/util" 12 | "strings" 13 | ) 14 | 15 | type WebSocket struct { 16 | } 17 | 18 | //ws接收消息 19 | func (this *WebSocket) ConnHandle(msf *Msf, sess *Session) { 20 | defer func() { 21 | msf.SessionMaster.DelSessionById(sess.Id) 22 | //调用断开链接事件 23 | msf.EventPool.OnClose(sess.Id) 24 | }() 25 | 26 | if this.Handshake(sess) == false { 27 | return 28 | } 29 | 30 | var ( 31 | buf []byte 32 | err error 33 | fin byte 34 | opcode byte 35 | mask byte 36 | mKey []byte 37 | length uint64 38 | l uint16 39 | payload byte 40 | tembuf []byte 41 | ) 42 | 43 | for { 44 | buf = make([]byte, 2) 45 | _, err = io.ReadFull(sess.Con, buf) 46 | if err != nil { 47 | break 48 | } 49 | fin = buf[0] >> 7 50 | opcode = buf[0] & 0xf 51 | if opcode == 8 { 52 | break 53 | } 54 | mask = buf[1] >> 7 55 | payload = buf[1] & 0x7f 56 | switch { 57 | case payload < 126: 58 | length = uint64(payload) 59 | case payload == 126: 60 | buf = make([]byte, 2) 61 | io.ReadFull(sess.Con, buf) 62 | binary.Read(bytes.NewReader(buf), binary.BigEndian, &l) 63 | length = uint64(l) 64 | case payload == 127: 65 | buf = make([]byte, 8) 66 | io.ReadFull(sess.Con, buf) 67 | binary.Read(bytes.NewReader(buf), binary.BigEndian, &length) 68 | } 69 | if mask == 1 { 70 | mKey = make([]byte, 4) 71 | io.ReadFull(sess.Con, mKey) 72 | } 73 | buf = make([]byte, length) 74 | io.ReadFull(sess.Con, buf) 75 | if mask == 1 { 76 | for i, v := range buf { 77 | buf[i] = v ^ mKey[i%4] 78 | } 79 | } 80 | //更新最近接收到消息的时间 81 | sess.updateTime() 82 | if len(buf) == 0 { 83 | continue 84 | } 85 | tembuf = append(tembuf,buf...) 86 | if fin == 0 { 87 | continue 88 | } 89 | //把请求的到数据转化为map 90 | requestData := util.String2Map(string(tembuf)) 91 | tembuf = make([]byte,0) 92 | //路由调用 93 | if msf.Hook(sess.Id,requestData) == false { 94 | return 95 | } 96 | } 97 | } 98 | 99 | //websocket 打包事件 100 | func (this *WebSocket) Pack(data []byte) []byte { 101 | length := len(data) 102 | frame := []byte{129} 103 | switch { 104 | case length < 126: 105 | frame = append(frame, byte(length)) 106 | case length <= 0xffff: 107 | buf := make([]byte, 2) 108 | binary.BigEndian.PutUint16(buf, uint16(length)) 109 | frame = append(frame, byte(126)) 110 | frame = append(frame, buf...) 111 | case uint64(length) <= 0xffffffffffffffff: 112 | buf := make([]byte, 8) 113 | binary.BigEndian.PutUint64(buf, uint64(length)) 114 | frame = append(frame, byte(127)) 115 | frame = append(frame, buf...) 116 | default: 117 | return []byte{} 118 | } 119 | frame = append(frame, data...) 120 | return frame 121 | } 122 | 123 | //握手包 124 | func (this *WebSocket) Handshake(sess *Session) bool { 125 | reader := bufio.NewReader(sess.Con) 126 | key := "" 127 | str := "" 128 | for { 129 | line, _, err := reader.ReadLine() 130 | if err != nil { 131 | log.Fatal(err) 132 | return false 133 | } 134 | if len(line) == 0 { 135 | break 136 | } 137 | str = string(line) 138 | if strings.HasPrefix(str, "Sec-WebSocket-Key") { 139 | key = str[19:43] 140 | } 141 | } 142 | sha := sha1.New() 143 | io.WriteString(sha, key+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11") 144 | key = base64.StdEncoding.EncodeToString(sha.Sum(nil)) 145 | 146 | header := "HTTP/1.1 101 Switching Protocols\r\n" + 147 | "Connection: Upgrade\r\n" + 148 | "Sec-WebSocket-Version: 13\r\n" + 149 | "Sec-WebSocket-Accept: " + key + "\r\n" + 150 | "Upgrade: websocket\r\n\r\n" 151 | sess.Con.Write([]byte(header)) 152 | return true 153 | } 154 | -------------------------------------------------------------------------------- /routers.go: -------------------------------------------------------------------------------- 1 | package microSocket 2 | 3 | import ( 4 | "net" 5 | "reflect" 6 | ) 7 | 8 | const ( 9 | DEFAULTACTION = "Default" 10 | BEFORACTION = "BeforeRequest" 11 | AFTERACTION = "AfterRequest" 12 | ) 13 | 14 | type module interface { 15 | Default(fd uint32,data map[string]string) bool 16 | BeforeRequest(fd uint32,data map[string]string) bool 17 | AfterRequest(fd uint32,data map[string]string) bool 18 | } 19 | 20 | type eventer interface { 21 | OnHandel(fd uint32, conn net.Conn) bool 22 | OnClose(fd uint32) 23 | OnMessage(fd uint32, msg map[string]string) bool 24 | } 25 | 26 | type RoutersMap struct { 27 | pools map[string] func(uint32,map[string]string) bool 28 | strPools map[string] map[string] func(uint32,map[string]string) bool 29 | structs map[string] module 30 | events eventer 31 | } 32 | 33 | func NewRoutersMap() *RoutersMap{ 34 | return &RoutersMap{ 35 | pools :make(map[string]func(uint32,map[string]string) bool), 36 | strPools:make(map[string]map[string] func(uint32,map[string]string) bool), 37 | structs : make(map[string]module), 38 | } 39 | } 40 | 41 | //注册事件 42 | func (this *RoutersMap) RegisterEvent (events eventer) { 43 | this.events = events 44 | } 45 | 46 | //注册单个逻辑 47 | func (this *RoutersMap) RegisterFun (methodName string ,funcs func(uint32 ,map[string]string) bool) bool { 48 | if _, exit := this.pools[methodName]; !exit { 49 | this.pools[methodName] = funcs 50 | return true 51 | } 52 | return false 53 | } 54 | 55 | //结构体 注册 56 | func (this *RoutersMap) RegisterStructFun (moduleName string,mod module) bool { 57 | if _, exit := this.strPools[moduleName]; exit { 58 | return false 59 | } 60 | this.strPools[moduleName] = make(map[string] func(uint32,map[string]string) bool) 61 | this.structs[moduleName] = mod 62 | 63 | temType := reflect.TypeOf(mod) 64 | temValue := reflect.ValueOf(mod) 65 | for i := 0 ; i < temType.NumMethod(); i++ { 66 | tem := temValue.Method(i).Interface() 67 | if temFunc ,ok := tem.(func(uint32, map[string]string) bool); ok { 68 | this.strPools[moduleName][temType.Method(i).Name] = temFunc 69 | } 70 | } 71 | return true 72 | } 73 | 74 | func (this *RoutersMap) HookAction (funcionName string,fd uint32, data map[string]string) bool{ 75 | if action ,exit := this.pools[funcionName]; exit { 76 | return action(fd, data) 77 | } else { 78 | return false 79 | } 80 | } 81 | 82 | func (this *RoutersMap) HookModule(mouleName string, method string,fd uint32, data map[string]string) bool { 83 | if _, exit := this.strPools[mouleName]; !exit { 84 | return false 85 | } 86 | 87 | if this.strPools[mouleName][BEFORACTION](fd, data) == false { 88 | return false 89 | } 90 | if action, exit := this.strPools[mouleName][method]; exit { 91 | if action(fd, data) == false { 92 | return false 93 | } 94 | } else { 95 | if this.strPools[mouleName][DEFAULTACTION](fd, data) == false { 96 | return false 97 | } 98 | } 99 | if this.strPools[mouleName][AFTERACTION](fd, data) == false { 100 | return false 101 | } 102 | return true 103 | } 104 | 105 | func (this *RoutersMap) OnClose(fd uint32) { 106 | if this.events != nil { 107 | this.events.OnClose(fd) 108 | } 109 | } 110 | 111 | func (this *RoutersMap) OnHandel(fd uint32, conn net.Conn) bool { 112 | if this.events != nil { 113 | return this.events.OnHandel(fd, conn) 114 | } 115 | return true 116 | } 117 | 118 | func (this *RoutersMap) OnMessage(fd uint32, msg map[string]string) bool { 119 | if this.events != nil { 120 | return this.events.OnMessage(fd , msg) 121 | } 122 | return true 123 | } 124 | 125 | -------------------------------------------------------------------------------- /server.go: -------------------------------------------------------------------------------- 1 | package microSocket 2 | 3 | import ( 4 | "log" 5 | "net" 6 | ) 7 | 8 | type SocketTypes interface{ 9 | ConnHandle(msf *Msf,sess *Session) 10 | Pack(data []byte)[]byte 11 | } 12 | 13 | type Msf struct { 14 | EventPool *RoutersMap 15 | SessionMaster *SessionM 16 | SocketType SocketTypes 17 | } 18 | 19 | func NewMsf(socketType SocketTypes) *Msf { 20 | msf := &Msf{ 21 | EventPool : NewRoutersMap(), 22 | SocketType: socketType, 23 | } 24 | msf.SessionMaster = NewSessonM(msf) 25 | return msf 26 | } 27 | 28 | func (this *Msf) Listening(address string) { 29 | tcpListen, err := net.Listen("tcp", address) 30 | 31 | if err != nil { 32 | panic(err) 33 | } 34 | go this.SessionMaster.HeartBeat(2) 35 | fd := uint32(0) 36 | for { 37 | conn, err := tcpListen.Accept() 38 | if err != nil { 39 | log.Println(err) 40 | continue 41 | } 42 | //调用握手事件 43 | if this.EventPool.OnHandel(fd, conn) == false { 44 | continue 45 | } 46 | this.SessionMaster.SetSession(fd, conn) 47 | go this.SocketType.ConnHandle(this,this.SessionMaster.GetSessionById(fd)) 48 | fd++ 49 | } 50 | } 51 | 52 | func (this *Msf) Hook(fd uint32,requestData map[string]string)bool { 53 | //调用接收消息事件 54 | if this.EventPool.OnMessage(fd, requestData) == false { 55 | return false 56 | } 57 | //requestData["fd"] = fmt.Sprintf("%d", fd) 58 | //路由 59 | if actionName, exit := requestData["action"]; exit { 60 | if this.EventPool.HookAction(actionName, fd, requestData) == false { 61 | return false 62 | } 63 | } else { 64 | if this.EventPool.HookModule(requestData["module"],requestData["method"], fd, requestData) == false { 65 | return false 66 | } 67 | } 68 | return true 69 | } 70 | 71 | 72 | -------------------------------------------------------------------------------- /session.go: -------------------------------------------------------------------------------- 1 | package microSocket 2 | 3 | import ( 4 | "log" 5 | "net" 6 | "sync" 7 | "time" 8 | ) 9 | 10 | //---------------------------------------------一个session代表一个连接-------------------------------------------------- 11 | type Session struct { 12 | Id uint32 13 | Con net.Conn 14 | times int64 15 | lock sync.Mutex 16 | } 17 | 18 | func NewSession(id uint32, con net.Conn) *Session { 19 | return &Session{ 20 | Id : id, 21 | Con: con, 22 | times: time.Now().Unix(), 23 | } 24 | } 25 | 26 | func (this *Session) write(msg string) error { 27 | this.lock.Lock() 28 | defer this.lock.Unlock() 29 | _ ,errs := this.Con.Write([]byte(msg)) 30 | return errs 31 | } 32 | 33 | func (this *Session)close(){ 34 | this.Con.Close() 35 | } 36 | 37 | func (this *Session)updateTime(){ 38 | this.times = time.Now().Unix() 39 | } 40 | //---------------------------------------------------SESSION管理类------------------------------------------------------ 41 | 42 | type SessionM struct { 43 | isWebSocket bool 44 | ser *Msf 45 | sessions sync.Map 46 | } 47 | 48 | func NewSessonM(msf *Msf) *SessionM { 49 | if msf == nil { 50 | return nil 51 | } 52 | 53 | return &SessionM{ 54 | ser : msf, 55 | } 56 | } 57 | 58 | func (this *SessionM) GetSessionById(id uint32) *Session { 59 | tem ,exit := this.sessions.Load(id) 60 | if exit { 61 | if sess, ok := tem.(*Session) ; ok { 62 | return sess 63 | } 64 | } 65 | return nil 66 | } 67 | 68 | func (this *SessionM) SetSession(fd uint32, conn net.Conn) { 69 | sess := NewSession(fd, conn) 70 | this.sessions.Store(fd,sess) 71 | } 72 | 73 | //关闭连接并删除 74 | func (this *SessionM) DelSessionById(id uint32) { 75 | tem ,exit := this.sessions.Load(id) 76 | if exit { 77 | if sess, ok := tem.(*Session) ; ok { 78 | sess.close() 79 | } 80 | } 81 | this.sessions.Delete(id) 82 | } 83 | 84 | //向所有客户端发送消息 85 | func (this *SessionM) WriteToAll(msg []byte) { 86 | msg = this.ser.SocketType.Pack(msg) 87 | this.sessions.Range(func(key,val interface{})bool{ 88 | if val, ok := val.(*Session); ok { 89 | if err := val.write(string(msg)); err != nil { 90 | this.DelSessionById(key.(uint32)) 91 | log.Println(err) 92 | } 93 | } 94 | return true 95 | }) 96 | } 97 | 98 | //向单个客户端发送信息 99 | func (this *SessionM) WriteByid(id uint32, msg []byte) bool { 100 | //把消息打包 101 | msg = this.ser.SocketType.Pack(msg) 102 | 103 | tem ,exit := this.sessions.Load(id) 104 | if exit { 105 | if sess, ok := tem.(*Session) ; ok { 106 | if err := sess.write(string(msg)); err == nil { 107 | return true 108 | } 109 | } 110 | } 111 | this.DelSessionById(id) 112 | return false 113 | } 114 | 115 | //心跳检测 每秒遍历一次 查看所有sess 上次接收消息时间 如果超过 num 就删除该 sess 116 | func (this *SessionM)HeartBeat(num int64){ 117 | for { 118 | time.Sleep(time.Second) 119 | this.sessions.Range(func (key,val interface{})bool { 120 | tem , ok := val.(*Session) 121 | if !ok { 122 | return true 123 | } 124 | 125 | if time.Now().Unix() - tem.times > num { 126 | this.DelSessionById(key.(uint32)) 127 | } 128 | return true 129 | }) 130 | 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /util/StringMap.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | //把map转化为string "a:b|" 9 | func Map2String(msg map[string]string) string { 10 | if len(msg) == 0 { 11 | return "" 12 | } 13 | data := "" 14 | for i, v := range msg { 15 | data += fmt.Sprintf("%v:%v|", i, v) 16 | } 17 | return data[:len(data)-1] 18 | } 19 | 20 | //把string转化为map 21 | func String2Map(msg string) map[string]string { 22 | data := make(map[string]string) 23 | tempData := strings.Split(msg, "|") 24 | 25 | if len(tempData) < 1 { 26 | return data 27 | } 28 | 29 | for _, v := range tempData { 30 | tempValue := strings.Split(v, ":") 31 | if len(tempValue) <= 1 { 32 | continue 33 | } 34 | data[tempValue[0]] = tempValue[1] 35 | } 36 | 37 | return data 38 | } 39 | -------------------------------------------------------------------------------- /util/chanMap.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | var ( 4 | ADD interface{} = 1 5 | DEL interface{} = 2 6 | GET interface{} = 3 7 | ) 8 | 9 | 10 | type safeMap struct { 11 | Msq chan *[3] interface{} //['type','id','value',channle] 12 | data map[interface{}]interface{} 13 | chanl chan interface{} 14 | } 15 | 16 | func NewSafeMap() *safeMap { 17 | tem := &safeMap{} 18 | tem.init() 19 | return tem 20 | } 21 | 22 | func (this *safeMap) init() { 23 | this.Msq = make(chan *[3]interface{},10) 24 | this.data = make(map[interface{}]interface{}) 25 | this.chanl = make(chan interface{},0) 26 | go this.run() 27 | } 28 | 29 | func (this *safeMap) run() { 30 | for { 31 | select { 32 | case msg := <- this.Msq : 33 | switch msg[0] { 34 | case ADD : 35 | this.dataAdd(msg[1],msg[2]) 36 | case DEL : 37 | this.dataDel(msg[1]) 38 | case GET : 39 | this.dataGet(msg[1]) 40 | } 41 | } 42 | } 43 | } 44 | 45 | func (this *safeMap) msqChan (typ,id,val interface{}) *[3]interface{}{ 46 | return &[...]interface{}{typ,id,val} 47 | } 48 | 49 | //保存 或者更新元素 50 | func (this *safeMap) dataAdd (id , value interface{}) { 51 | this.data[id] = value 52 | } 53 | 54 | //删除元素 55 | func (this *safeMap) dataDel (id interface{}) { 56 | delete(this.data,id) 57 | } 58 | 59 | //获得元素 60 | func (this *safeMap) dataGet (id interface{}) { 61 | if val ,exit := this.data[id] ;exit { 62 | this.chanl <- val 63 | return 64 | } 65 | this.chanl <- nil 66 | } 67 | 68 | //----------------------------------------------------对外接口-------------------------------- 69 | func (this *safeMap) Add (id ,value interface{}) { 70 | this.Msq <- this.msqChan(ADD,id,value) 71 | } 72 | 73 | func (this *safeMap) Del (id interface{}) { 74 | this.Msq <- this.msqChan(DEL,id ,nil) 75 | } 76 | 77 | func (this *safeMap) Get (id interface{}) interface{} { 78 | this.Msq <- this.msqChan(GET,id,nil) 79 | res := <- this.chanl 80 | return res 81 | } 82 | 83 | //获得 长度 84 | func (this *safeMap) GetLength() uint32{ 85 | return uint32(len(this.data)) 86 | } 87 | 88 | /* 89 | func main() { 90 | sa := NewSafeMap() 91 | 92 | // sa.Add(1,1) 93 | sa.Add(2,3) 94 | fmt.Println(2,sa.Get(2)) 95 | sa.Del(2) 96 | fmt.Println(2,sa.Get(2)) 97 | } 98 | 99 | */ -------------------------------------------------------------------------------- /util/file.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | ) 7 | 8 | func WriteFile(path string, content string) error { 9 | fileObj, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) 10 | if err != nil { 11 | return err 12 | } 13 | defer fileObj.Close() 14 | contents := []byte(content) 15 | if _, err := fileObj.Write(contents); err != nil { 16 | return err 17 | } 18 | return nil 19 | } 20 | 21 | func WriteFileAppend(path string, content string) error { 22 | fileObj, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) 23 | if err != nil { 24 | return err 25 | } 26 | defer fileObj.Close() 27 | contents := []byte(content) 28 | if _, err := fileObj.Write(contents); err != nil { 29 | return err 30 | } 31 | return nil 32 | } 33 | 34 | //读取文件 35 | func ReadFile(path string) (string, error) { 36 | fi, err := os.Open(path) 37 | if err != nil { 38 | return "", err 39 | } 40 | defer fi.Close() 41 | fd, err := ioutil.ReadAll(fi) 42 | return string(fd), nil 43 | } 44 | 45 | //删除指定文件夹或者文件 46 | func RemoveFile(path string) error { 47 | if err := os.RemoveAll(path); err != nil { 48 | return err 49 | } 50 | return nil 51 | } 52 | 53 | //创建指定路径文件 54 | func MakeDirAll(path string) error { 55 | if err := os.MkdirAll(path, 0755); err != nil { 56 | return err 57 | } 58 | return nil 59 | } 60 | 61 | //查看指定目录下面所有文件 62 | func ReadDir(path string) ([]string, error) { 63 | if dirList, err := ioutil.ReadDir(path); err != nil { 64 | return nil, err 65 | } else { 66 | var fileName = make([]string, len(dirList)) 67 | for i, v := range dirList { 68 | if v.IsDir() { 69 | fileName[i] = "dir:" + v.Name() 70 | } else { 71 | fileName[i] = "file:" + v.Name() 72 | } 73 | 74 | } 75 | return fileName, nil 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /util/safeMap.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import "sync" 4 | 5 | type SafeMap struct { 6 | Data map[string]interface{} 7 | Lock sync.RWMutex 8 | } 9 | 10 | func (this *SafeMap) Get(k string) interface{} { 11 | this.Lock.RLock() 12 | defer this.Lock.RUnlock() 13 | if v, exit := this.Data[k]; exit { 14 | return v 15 | } 16 | return nil 17 | } 18 | 19 | func (this *SafeMap) Set(k string, v interface{}) { 20 | this.Lock.Lock() 21 | defer this.Lock.Unlock() 22 | if this.Data == nil { 23 | this.Data = make(map[string]interface{}) 24 | } 25 | this.Data[k] = v 26 | } 27 | 28 | 29 | --------------------------------------------------------------------------------