├── .gitignore ├── LICENSE ├── async_server.go ├── bucket.go ├── callback.go ├── examples ├── defaultServer │ ├── callback.go │ ├── client.go │ ├── main.go │ └── server.go └── echoServer │ ├── callback.go │ ├── protocol.go │ └── server.go ├── packet.go ├── protocol.go └── tcp_conn.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | .idea 10 | 11 | # Architecture specific extensions/prefixes 12 | *.[568vq] 13 | [568vq].out 14 | 15 | *.cgo1.go 16 | *.cgo2.c 17 | _cgo_defun.c 18 | _cgo_gotypes.go 19 | _cgo_export.* 20 | 21 | _testmain.go 22 | 23 | *.exe 24 | *.test 25 | *.prof 26 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /async_server.go: -------------------------------------------------------------------------------- 1 | package tcp 2 | 3 | import ( 4 | "errors" 5 | "log" 6 | "net" 7 | "os" 8 | "time" 9 | ) 10 | 11 | const ( 12 | //tcp conn max packet size 13 | defaultMaxPacketSize = 1024 << 10 //1MB 14 | 15 | readChanSize = 100 16 | writeChanSize = 100 17 | ) 18 | 19 | var ( 20 | logger *log.Logger 21 | ) 22 | 23 | func init() { 24 | logger = log.New(os.Stdout, "", log.Lshortfile) 25 | } 26 | 27 | //AsyncTCPServer 结构定义 28 | type AsyncTCPServer struct { 29 | //TCP address to listen on 30 | tcpAddr string 31 | 32 | //the listener 33 | listener *net.TCPListener 34 | 35 | //callback is an interface 36 | //it's used to process the connect establish, close and data receive 37 | callback CallBack 38 | protocol Protocol 39 | 40 | //if srv is shutdown, close the channel used to inform all session to exit. 41 | exitChan chan struct{} 42 | 43 | readDeadline, writeDeadline time.Duration 44 | bucket *TCPConnBucket 45 | } 46 | 47 | //NewAsyncTCPServer 返回一个AsyncTCPServer实例 48 | func NewAsyncTCPServer(tcpAddr string, callback CallBack, protocol Protocol) *AsyncTCPServer { 49 | return &AsyncTCPServer{ 50 | tcpAddr: tcpAddr, 51 | callback: callback, 52 | protocol: protocol, 53 | 54 | bucket: NewTCPConnBucket(), 55 | exitChan: make(chan struct{}), 56 | } 57 | } 58 | 59 | //ListenAndServe 使用AsyncTCPServer的tcpAddr创建TCPListner并调用Server()方法开启监听 60 | func (srv *AsyncTCPServer) ListenAndServe() error { 61 | tcpAddr, err := net.ResolveTCPAddr("tcp4", srv.tcpAddr) 62 | if err != nil { 63 | return err 64 | } 65 | ln, err := net.ListenTCP("tcp4", tcpAddr) 66 | if err != nil { 67 | return err 68 | } 69 | go srv.Serve(ln) 70 | return nil 71 | } 72 | 73 | //Serve 使用指定的TCPListener开启监听 74 | func (srv *AsyncTCPServer) Serve(l *net.TCPListener) error { 75 | srv.listener = l 76 | defer func() { 77 | if r := recover(); r != nil { 78 | log.Println("Serve error", r) 79 | } 80 | srv.listener.Close() 81 | }() 82 | 83 | //清理无效连接 84 | go func() { 85 | for { 86 | srv.removeClosedTCPConn() 87 | time.Sleep(time.Millisecond * 10) 88 | } 89 | }() 90 | 91 | var tempDelay time.Duration 92 | for { 93 | select { 94 | case <-srv.exitChan: 95 | return errors.New("TCPServer Closed") 96 | default: 97 | } 98 | conn, err := srv.listener.AcceptTCP() 99 | if err != nil { 100 | if ne, ok := err.(net.Error); ok && ne.Temporary() { 101 | if tempDelay == 0 { 102 | tempDelay = 5 * time.Millisecond 103 | } else { 104 | tempDelay *= 2 105 | } 106 | if max := 1 * time.Second; tempDelay > max { 107 | tempDelay = max 108 | } 109 | time.Sleep(tempDelay) 110 | continue 111 | } 112 | log.Println("ln error:", err.Error()) 113 | return err 114 | } 115 | tempDelay = 0 116 | tcpConn := srv.newTCPConn(conn, srv.callback, srv.protocol) 117 | tcpConn.setReadDeadline(srv.readDeadline) 118 | tcpConn.setWriteDeadline(srv.writeDeadline) 119 | srv.bucket.Put(tcpConn.GetRemoteAddr().String(), tcpConn) 120 | } 121 | } 122 | 123 | func (srv *AsyncTCPServer) newTCPConn(conn *net.TCPConn, callback CallBack, protocol Protocol) *TCPConn { 124 | if callback == nil { 125 | // if the handler is nil, use srv handler 126 | callback = srv.callback 127 | } 128 | 129 | if protocol == nil { 130 | protocol = srv.protocol 131 | } 132 | 133 | c := NewTCPConn(conn, callback, protocol) 134 | c.Serve() 135 | return c 136 | } 137 | 138 | //Connect 使用指定的callback和protocol连接其他TCPServer,返回TCPConn 139 | func (srv *AsyncTCPServer) Connect(ip string, callback CallBack, protocol Protocol) (*TCPConn, error) { 140 | tcpAddr, err := net.ResolveTCPAddr("tcp", ip) 141 | if err != nil { 142 | return nil, err 143 | } 144 | conn, err := net.DialTCP("tcp", nil, tcpAddr) 145 | if err != nil { 146 | return nil, err 147 | } 148 | 149 | tcpConn := srv.newTCPConn(conn, callback, protocol) 150 | return tcpConn, nil 151 | 152 | } 153 | 154 | //Close 首先关闭所有连接,然后关闭TCPServer 155 | func (srv *AsyncTCPServer) Close() { 156 | defer srv.listener.Close() 157 | for _, c := range srv.bucket.GetAll() { 158 | if !c.IsClosed() { 159 | c.Close() 160 | } 161 | } 162 | } 163 | 164 | func (srv *AsyncTCPServer) removeClosedTCPConn() { 165 | select { 166 | case <-srv.exitChan: 167 | return 168 | default: 169 | srv.bucket.removeClosedTCPConn() 170 | } 171 | } 172 | 173 | func (srv *AsyncTCPServer) GetAllTCPConn() []*TCPConn { 174 | conns := []*TCPConn{} 175 | for _, conn := range srv.bucket.GetAll() { 176 | conns = append(conns, conn) 177 | } 178 | return conns 179 | } 180 | 181 | func (srv *AsyncTCPServer) GetTCPConn(key string) *TCPConn { 182 | return srv.bucket.Get(key) 183 | } 184 | 185 | func (srv *AsyncTCPServer) SetReadDeadline(t time.Duration) { 186 | srv.readDeadline = t 187 | } 188 | 189 | func (srv *AsyncTCPServer) SetWriteDeadline(t time.Duration) { 190 | srv.writeDeadline = t 191 | } 192 | -------------------------------------------------------------------------------- /bucket.go: -------------------------------------------------------------------------------- 1 | package tcp 2 | 3 | import ( 4 | "sync" 5 | ) 6 | 7 | //TCPConnBucket 用来存放和管理TCPConn连接 8 | type TCPConnBucket struct { 9 | m map[string]*TCPConn 10 | mu *sync.RWMutex 11 | } 12 | 13 | func NewTCPConnBucket() *TCPConnBucket { 14 | tcb := &TCPConnBucket{ 15 | m: make(map[string]*TCPConn), 16 | mu: new(sync.RWMutex), 17 | } 18 | return tcb 19 | } 20 | 21 | func (b *TCPConnBucket) Put(id string, c *TCPConn) { 22 | b.mu.Lock() 23 | if conn, ok := b.m[id]; ok { 24 | conn.Close() 25 | } 26 | b.m[id] = c 27 | b.mu.Unlock() 28 | } 29 | 30 | func (b *TCPConnBucket) Get(id string) *TCPConn { 31 | b.mu.RLock() 32 | defer b.mu.RUnlock() 33 | if conn, ok := b.m[id]; ok { 34 | return conn 35 | } 36 | return nil 37 | } 38 | 39 | func (b *TCPConnBucket) Delete(id string) { 40 | b.mu.Lock() 41 | delete(b.m, id) 42 | b.mu.Unlock() 43 | } 44 | func (b *TCPConnBucket) GetAll() map[string]*TCPConn { 45 | b.mu.RLock() 46 | defer b.mu.RUnlock() 47 | m := make(map[string]*TCPConn, len(b.m)) 48 | for k, v := range b.m { 49 | m[k] = v 50 | } 51 | return m 52 | } 53 | 54 | func (b *TCPConnBucket) removeClosedTCPConn() { 55 | removeKey := make(map[string]struct{}) 56 | for key, conn := range b.GetAll() { 57 | if conn.IsClosed() { 58 | removeKey[key] = struct{}{} 59 | } 60 | } 61 | for key := range removeKey { 62 | b.Delete(key) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /callback.go: -------------------------------------------------------------------------------- 1 | package tcp 2 | 3 | //CallBack 是一个回调接口,用于连接的各种事件处理 4 | type CallBack interface { 5 | //链接建立回调 6 | OnConnected(conn *TCPConn) 7 | //消息处理回调 8 | OnMessage(conn *TCPConn, p Packet) 9 | //链接断开回调 10 | OnDisconnected(conn *TCPConn) 11 | //错误回调 12 | OnError(err error) 13 | } 14 | -------------------------------------------------------------------------------- /examples/defaultServer/callback.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/wuyingsong/tcp" 7 | ) 8 | 9 | type callback struct{} 10 | 11 | func (c *callback) OnMessage(conn *tcp.TCPConn, p tcp.Packet) { 12 | log.Println("server receive:", string(p.Bytes()[1:])) 13 | } 14 | 15 | func (c *callback) OnConnected(conn *tcp.TCPConn) { 16 | log.Println("new conn:", conn.GetRemoteAddr().String()) 17 | } 18 | 19 | func (c *callback) OnDisconnected(conn *tcp.TCPConn) { 20 | log.Printf("%s disconnected\n", conn.GetRemoteIPAddress()) 21 | } 22 | 23 | func (c *callback) OnError(err error) { 24 | log.Println(err) 25 | } 26 | -------------------------------------------------------------------------------- /examples/defaultServer/client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net" 7 | "time" 8 | 9 | "github.com/wuyingsong/tcp" 10 | ) 11 | 12 | func startClient(callback tcp.CallBack, protocol tcp.Protocol) { 13 | tcpAddr, err := net.ResolveTCPAddr("tcp", "localhost:9001") 14 | if err != nil { 15 | panic(err) 16 | } 17 | conn, err := net.DialTCP("tcp", nil, tcpAddr) 18 | if err != nil { 19 | panic(err) 20 | } 21 | tc := tcp.NewTCPConn(conn, callback, protocol) 22 | log.Println(tc.Serve()) 23 | i := 0 24 | for { 25 | if tc.IsClosed() { 26 | break 27 | } 28 | msg := fmt.Sprintf("hello %d", i) 29 | log.Println("client send: ", msg) 30 | tc.AsyncWritePacket(&tcp.DefaultPacket{Type: 1, Body: []byte(msg)}) 31 | i++ 32 | time.Sleep(time.Second) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /examples/defaultServer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "github.com/wuyingsong/tcp" 4 | 5 | func main() { 6 | protocol := &tcp.DefaultProtocol{} 7 | protocol.SetMaxPacketSize(100) 8 | startServer(&callback{}, protocol) 9 | startClient(&callback{}, protocol) 10 | select {} 11 | } 12 | -------------------------------------------------------------------------------- /examples/defaultServer/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/wuyingsong/tcp" 5 | ) 6 | 7 | func startServer(callback tcp.CallBack, protocol tcp.Protocol) error { 8 | srv := tcp.NewAsyncTCPServer("localhost:9001", callback, protocol) 9 | return srv.ListenAndServe() 10 | } 11 | -------------------------------------------------------------------------------- /examples/echoServer/callback.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/wuyingsong/tcp" 7 | ) 8 | 9 | type EchoCallback struct{} 10 | 11 | func (ec *EchoCallback) OnConnected(conn *tcp.TCPConn) { 12 | log.Println("new conn: ", conn.GetRemoteIPAddress()) 13 | } 14 | func (ec *EchoCallback) OnMessage(conn *tcp.TCPConn, p tcp.Packet) { 15 | log.Printf("receive: %s", string(p.Bytes())) 16 | conn.AsyncWritePacket(p) 17 | } 18 | func (ec *EchoCallback) OnDisconnected(conn *tcp.TCPConn) { 19 | log.Printf("%s disconnected\n", conn.GetRemoteIPAddress()) 20 | } 21 | 22 | func (ec *EchoCallback) OnError(err error) { 23 | log.Println(err) 24 | } 25 | -------------------------------------------------------------------------------- /examples/echoServer/protocol.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "io" 6 | 7 | "github.com/wuyingsong/tcp" 8 | ) 9 | 10 | type EchoProtocol struct { 11 | data []byte 12 | } 13 | 14 | func (ep *EchoProtocol) Bytes() []byte { 15 | return ep.data 16 | } 17 | 18 | func (ep *EchoProtocol) ReadPacket(reader io.Reader) (tcp.Packet, error) { 19 | rd := bufio.NewReader(reader) 20 | bytesData, err := rd.ReadBytes('\n') 21 | if err != nil { 22 | return nil, err 23 | } 24 | return &EchoProtocol{data: bytesData}, nil 25 | } 26 | func (ep *EchoProtocol) WritePacket(writer io.Writer, msg tcp.Packet) error { 27 | _, err := writer.Write(msg.Bytes()) 28 | return err 29 | } 30 | -------------------------------------------------------------------------------- /examples/echoServer/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "time" 6 | 7 | "github.com/wuyingsong/tcp" 8 | ) 9 | 10 | func main() { 11 | srv := tcp.NewAsyncTCPServer("localhost:9001", &EchoCallback{}, &EchoProtocol{}) 12 | srv.SetReadDeadline(time.Second * 10) 13 | log.Println("start listen...") 14 | log.Println(srv.ListenAndServe()) 15 | select {} 16 | } 17 | -------------------------------------------------------------------------------- /packet.go: -------------------------------------------------------------------------------- 1 | package tcp 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | ) 7 | 8 | type Packet interface { 9 | Bytes() []byte 10 | } 11 | 12 | type PacketType byte 13 | 14 | type DefaultPacket struct { 15 | Type PacketType 16 | Body []byte 17 | } 18 | 19 | func NewDefaultPacket(t PacketType, body []byte) *DefaultPacket { 20 | return &DefaultPacket{ 21 | Type: t, 22 | Body: body, 23 | } 24 | } 25 | 26 | func (m *DefaultPacket) Bytes() []byte { 27 | var buf bytes.Buffer 28 | binary.Write(&buf, binary.BigEndian, m.Type) 29 | binary.Write(&buf, binary.BigEndian, m.Body) 30 | return buf.Bytes() 31 | } 32 | -------------------------------------------------------------------------------- /protocol.go: -------------------------------------------------------------------------------- 1 | package tcp 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "fmt" 7 | "io" 8 | ) 9 | 10 | type Protocol interface { 11 | ReadPacket(reader io.Reader) (Packet, error) 12 | WritePacket(writer io.Writer, msg Packet) error 13 | } 14 | 15 | const headLength = 4 16 | 17 | type DefaultProtocol struct { 18 | maxPacketSize uint32 19 | } 20 | 21 | func (p *DefaultProtocol) ReadPacket(reader io.Reader) (Packet, error) { 22 | return p.ReadPacketLimit(reader, p.maxPacketSize) 23 | } 24 | 25 | func (*DefaultProtocol) ReadPacketLimit(reader io.Reader, size uint32) (Packet, error) { 26 | head := make([]byte, headLength) 27 | 28 | _, err := io.ReadFull(reader, head) 29 | if err != nil { 30 | return nil, err 31 | } 32 | 33 | packetLength := binary.BigEndian.Uint32(head) 34 | if size != 0 && packetLength > size { 35 | return nil, fmt.Errorf("packet too large(%v > %v)", packetLength, size) 36 | } 37 | 38 | buf := make([]byte, packetLength) 39 | _, err = io.ReadFull(reader, buf) 40 | if err != nil { 41 | return nil, err 42 | } 43 | return NewDefaultPacket(PacketType(buf[0]), buf[1:]), nil 44 | } 45 | func (*DefaultProtocol) WritePacket(writer io.Writer, p Packet) error { 46 | var buf bytes.Buffer 47 | head := make([]byte, 4) 48 | data := p.Bytes() 49 | binary.BigEndian.PutUint32(head, uint32(len(data))) 50 | binary.Write(&buf, binary.BigEndian, head) 51 | binary.Write(&buf, binary.BigEndian, data) 52 | _, err := writer.Write(buf.Bytes()) 53 | return err 54 | } 55 | 56 | func (p *DefaultProtocol) SetMaxPacketSize(n uint32) { 57 | p.maxPacketSize = n 58 | } 59 | -------------------------------------------------------------------------------- /tcp_conn.go: -------------------------------------------------------------------------------- 1 | package tcp 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "io" 7 | "net" 8 | "strings" 9 | "sync" 10 | "sync/atomic" 11 | "time" 12 | ) 13 | 14 | var ( 15 | ErrConnClosing = errors.New("use of closed network connection") 16 | ErrBufferFull = errors.New("the async send buffer is full") 17 | ErrWriteTimeout = errors.New("async write packet timeout") 18 | ) 19 | 20 | type TCPConn struct { 21 | callback CallBack 22 | protocol Protocol 23 | 24 | conn *net.TCPConn 25 | readChan chan Packet 26 | writeChan chan Packet 27 | 28 | readDeadline time.Duration 29 | writeDeadline time.Duration 30 | 31 | exitChan chan struct{} 32 | closeOnce sync.Once 33 | exitFlag int32 34 | extraData map[string]interface{} 35 | } 36 | 37 | func NewTCPConn(conn *net.TCPConn, callback CallBack, protocol Protocol) *TCPConn { 38 | c := &TCPConn{ 39 | conn: conn, 40 | callback: callback, 41 | protocol: protocol, 42 | 43 | readChan: make(chan Packet, readChanSize), 44 | writeChan: make(chan Packet, writeChanSize), 45 | 46 | exitChan: make(chan struct{}), 47 | exitFlag: 0, 48 | } 49 | return c 50 | } 51 | 52 | func (c *TCPConn) Serve() error { 53 | defer func() { 54 | if r := recover(); r != nil { 55 | logger.Println("tcp conn(%v) Serve error, %v ", c.GetRemoteIPAddress(), r) 56 | } 57 | }() 58 | if c.callback == nil || c.protocol == nil { 59 | err := fmt.Errorf("callback and protocol are not allowed to be nil") 60 | c.Close() 61 | return err 62 | } 63 | atomic.StoreInt32(&c.exitFlag, 1) 64 | c.callback.OnConnected(c) 65 | go c.readLoop() 66 | go c.writeLoop() 67 | go c.handleLoop() 68 | return nil 69 | } 70 | 71 | func (c *TCPConn) readLoop() { 72 | defer func() { 73 | recover() 74 | c.Close() 75 | }() 76 | 77 | for { 78 | select { 79 | case <-c.exitChan: 80 | return 81 | default: 82 | if c.readDeadline > 0 { 83 | c.conn.SetReadDeadline(time.Now().Add(c.readDeadline)) 84 | } 85 | p, err := c.protocol.ReadPacket(c.conn) 86 | if err != nil { 87 | if err != io.EOF { 88 | c.callback.OnError(err) 89 | } 90 | return 91 | } 92 | c.readChan <- p 93 | } 94 | } 95 | } 96 | 97 | func (c *TCPConn) ReadPacket() (Packet, error) { 98 | if c.protocol == nil { 99 | return nil, errors.New("no protocol impl") 100 | } 101 | return c.protocol.ReadPacket(c.conn) 102 | } 103 | 104 | func (c *TCPConn) writeLoop() { 105 | defer func() { 106 | recover() 107 | c.Close() 108 | }() 109 | 110 | for pkt := range c.writeChan { 111 | if pkt == nil { 112 | continue 113 | } 114 | if c.writeDeadline > 0 { 115 | c.conn.SetWriteDeadline(time.Now().Add(c.writeDeadline)) 116 | } 117 | if err := c.protocol.WritePacket(c.conn, pkt); err != nil { 118 | c.callback.OnError(err) 119 | return 120 | } 121 | } 122 | } 123 | 124 | func (c *TCPConn) handleLoop() { 125 | defer func() { 126 | recover() 127 | c.Close() 128 | }() 129 | for p := range c.readChan { 130 | if p == nil { 131 | continue 132 | } 133 | c.callback.OnMessage(c, p) 134 | } 135 | } 136 | 137 | func (c *TCPConn) AsyncWritePacket(p Packet) error { 138 | if c.IsClosed() { 139 | return ErrConnClosing 140 | } 141 | select { 142 | case c.writeChan <- p: 143 | return nil 144 | default: 145 | return ErrBufferFull 146 | } 147 | } 148 | 149 | func (c *TCPConn) AsyncWritePacketWithTimeout(p Packet, sec int) error { 150 | if c.IsClosed() { 151 | return ErrConnClosing 152 | } 153 | select { 154 | case c.writeChan <- p: 155 | return nil 156 | case <-time.After(time.Second * time.Duration(sec)): 157 | return ErrWriteTimeout 158 | } 159 | } 160 | 161 | func (c *TCPConn) Close() { 162 | c.closeOnce.Do(func() { 163 | atomic.StoreInt32(&c.exitFlag, 0) 164 | close(c.exitChan) 165 | close(c.writeChan) 166 | close(c.readChan) 167 | if c.callback != nil { 168 | c.callback.OnDisconnected(c) 169 | } 170 | c.conn.Close() 171 | }) 172 | } 173 | 174 | func (c *TCPConn) GetRawConn() *net.TCPConn { 175 | return c.conn 176 | } 177 | 178 | func (c *TCPConn) IsClosed() bool { 179 | return atomic.LoadInt32(&c.exitFlag) == 0 180 | } 181 | 182 | func (c *TCPConn) GetLocalAddr() net.Addr { 183 | return c.conn.LocalAddr() 184 | } 185 | 186 | //LocalIPAddress 返回socket连接本地的ip地址 187 | func (c *TCPConn) GetLocalIPAddress() string { 188 | return strings.Split(c.GetLocalAddr().String(), ":")[0] 189 | } 190 | 191 | func (c *TCPConn) GetRemoteAddr() net.Addr { 192 | return c.conn.RemoteAddr() 193 | } 194 | 195 | func (c *TCPConn) GetRemoteIPAddress() string { 196 | return strings.Split(c.GetRemoteAddr().String(), ":")[0] 197 | } 198 | 199 | func (c *TCPConn) setReadDeadline(t time.Duration) { 200 | c.readDeadline = t 201 | } 202 | 203 | func (c *TCPConn) setWriteDeadline(t time.Duration) { 204 | c.writeDeadline = t 205 | } 206 | 207 | func (c *TCPConn) SetExtraData(key string, data interface{}) { 208 | if c.extraData == nil { 209 | c.extraData = make(map[string]interface{}) 210 | } 211 | c.extraData[key] = data 212 | } 213 | 214 | func (c *TCPConn) GetExtraData(key string) interface{} { 215 | if data, ok := c.extraData[key]; ok { 216 | return data 217 | } 218 | return nil 219 | } 220 | --------------------------------------------------------------------------------