├── .gitignore ├── LICENSE ├── README.md ├── atomic ├── add │ └── add.go ├── atomic.go └── cas │ └── cas.go ├── bytes ├── bufferRead.go ├── bufferWrite.go └── text.txt ├── format └── sprintf.go ├── mutex └── main.go ├── mutex_cond └── cond.go ├── reflect └── reflect.go └── sokect ├── protocol └── protocol.go ├── sokect.go └── tcp ├── client.go └── server.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 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | -------------------------------------------------------------------------------- /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 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # learngo 2 | Golang一些学习案例代码分享 3 | #目录结构 4 | + mutex 锁的使用代码片段 第一版案例coding 5 | + mutex_cond 条件变量&锁组合使用 第二版案例coding 6 | + atomic 原子操作 第三版案例coding 7 | + bytes 缓冲器 8 | + reflect 反射 9 | + sokect sokect编程 10 | -------------------------------------------------------------------------------- /atomic/add/add.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync/atomic" 6 | ) 7 | 8 | func main(){ 9 | var i32 int32 10 | fmt.Println("=====old i32 value=====") 11 | fmt.Println(i32) 12 | //第一个参数值必须是一个指针类型的值,因为该函数需要获得被操作值在内存中的存放位置,以便施加特殊的CPU指令 13 | //结束时会返回原子操作后的新值 14 | newI32 := atomic.AddInt32(&i32,3) 15 | fmt.Println("=====new i32 value=====") 16 | fmt.Println(i32) 17 | fmt.Println(newI32) 18 | 19 | var i64 int64 20 | fmt.Println("=====old i64 value=====") 21 | fmt.Println(i64) 22 | newI64 := atomic.AddInt64(&i64,-3) 23 | fmt.Println("=====new i64 value=====") 24 | fmt.Println(i64) 25 | fmt.Println(newI64) 26 | 27 | } 28 | 29 | -------------------------------------------------------------------------------- /atomic/atomic.go: -------------------------------------------------------------------------------- 1 | // Go 之 原子操作 2 | // 3 | // Copyright (c) 2015 - Batu <1235355@qq.com> 4 | // 5 | // 创建一个文件存放数据,在同一时刻,可能会有多个Goroutine分别进行对此文件的写操作和读操作. 6 | // 每一次写操作都应该向这个文件写入若干个字节的数据,作为一个独立的数据块存在,这意味着写操作之间不能彼此干扰,写入的内容之间也不能出现穿插和混淆的情况 7 | // 每一次读操作都应该从这个文件中读取一个独立完整的数据块.它们读取的数据块不能重复,且需要按顺序读取. 8 | // 例如: 第一个读操作读取了数据块1,第二个操作就应该读取数据块2,第三个读操作则应该读取数据块3,以此类推 9 | // 对于这些读操作是否可以被同时执行,不做要求. 即使同时进行,也应该保持先后顺序. 10 | package main 11 | 12 | import ( 13 | "fmt" 14 | "sync" 15 | "sync/atomic" 16 | "time" 17 | "os" 18 | "errors" 19 | "io" 20 | ) 21 | 22 | //数据文件的接口类型 23 | type DataFile interface { 24 | // 读取一个数据块 25 | Read() (rsn int64, d Data, err error) 26 | // 写入一个数据块 27 | Write(d Data) (wsn int64, err error) 28 | // 获取最后读取的数据块的序列号 29 | Rsn() int64 30 | // 获取最后写入的数据块的序列号 31 | Wsn() int64 32 | // 获取数据块的长度 33 | DataLen() uint32 34 | } 35 | 36 | //数据类型 37 | type Data []byte 38 | 39 | //数据文件的实现类型 40 | type myDataFile struct { 41 | f *os.File //文件 42 | fmutex sync.RWMutex //被用于文件的读写锁 43 | rcond *sync.Cond //读操作需要用到的条件变量 44 | woffset int64 // 写操作需要用到的偏移量 45 | roffset int64 // 读操作需要用到的偏移量 46 | dataLen uint32 //数据块长度 47 | } 48 | 49 | //初始化DataFile类型值的函数,返回一个DataFile类型的值 50 | func NewDataFile(path string, dataLen uint32) (DataFile, error){ 51 | //f, err := os.OpenFile(path, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0666) 52 | f,err := os.Create(path) 53 | if err != nil { 54 | fmt.Println("Fail to find", f, "cServer start Failed") 55 | return nil, err 56 | } 57 | 58 | if dataLen == 0 { 59 | return nil, errors.New("Invalid data length!") 60 | } 61 | 62 | df := &myDataFile{ 63 | f : f, 64 | dataLen:dataLen, 65 | } 66 | //创建一个可用的条件变量(初始化),返回一个*sync.Cond类型的结果值,我们就可以调用该值拥有的三个方法Wait,Signal,Broadcast 67 | df.rcond = sync.NewCond(df.fmutex.RLocker()) 68 | return df, nil 69 | } 70 | 71 | //获取并更新读偏移量,根据读偏移量从文件中读取一块数据,把该数据块封装成一个Data类型值并将其作为结果值返回 72 | 73 | func (df *myDataFile) Read() (rsn int64, d Data, err error){ 74 | // 读取并更新读偏移量 75 | var offset int64 76 | for { 77 | offset = atomic.LoadInt64(&df.roffset) 78 | if atomic.CompareAndSwapInt64(&df.roffset, offset, (offset + int64(df.dataLen))){ 79 | break 80 | } 81 | } 82 | 83 | //读取一个数据块,最后读取的数据块序列号 84 | rsn = offset / int64(df.dataLen) 85 | bytes := make([]byte, df.dataLen) 86 | //读写锁:读锁定 87 | df.fmutex.RLock() 88 | defer df.fmutex.RUnlock() 89 | 90 | for { 91 | _, err = df.f.ReadAt(bytes, offset) 92 | if err != nil { 93 | if err == io.EOF { 94 | //暂时放弃fmutex的 读锁,并等待通知的到来 95 | df.rcond.Wait() 96 | continue 97 | } 98 | } 99 | break 100 | } 101 | d = bytes 102 | return 103 | } 104 | 105 | func (df *myDataFile) Write(d Data) (wsn int64, err error){ 106 | //读取并更新写的偏移量 107 | var offset int64 108 | for { 109 | offset = atomic.LoadInt64(&df.woffset) 110 | if atomic.CompareAndSwapInt64(&df.woffset, offset, (offset + int64(df.dataLen))){ 111 | break 112 | } 113 | } 114 | 115 | 116 | //写入一个数据块,最后写入数据块的序号 117 | wsn = offset / int64(df.dataLen) 118 | var bytes []byte 119 | if len(d) > int(df.dataLen){ 120 | bytes = d[0:df.dataLen] 121 | }else{ 122 | bytes = d 123 | } 124 | df.fmutex.Lock() 125 | defer df.fmutex.Unlock() 126 | _, err = df.f.Write(bytes) 127 | //发送通知 128 | df.rcond.Signal() 129 | return 130 | } 131 | 132 | func (df *myDataFile) Rsn() int64{ 133 | offset := atomic.LoadInt64(&df.roffset) 134 | return offset / int64(df.dataLen) 135 | } 136 | 137 | func (df *myDataFile) Wsn() int64{ 138 | offset := atomic.LoadInt64(&df.woffset) 139 | return offset / int64(df.dataLen) 140 | } 141 | 142 | func (df *myDataFile) DataLen() uint32 { 143 | return df.dataLen 144 | } 145 | 146 | func main(){ 147 | //简单测试下结果 148 | var dataFile DataFile 149 | dataFile,_ = NewDataFile("./mutex_2015_1.dat", 10) 150 | 151 | var d=map[int]Data{ 152 | 1:[]byte("batu_test1"), 153 | 2:[]byte("batu_tstt2"), 154 | 3:[]byte("batu_test3"), 155 | } 156 | 157 | //写入数据 158 | for i:= 1; i < 4; i++ { 159 | go func(i int){ 160 | wsn,_ := dataFile.Write(d[i]) 161 | fmt.Println("write i=", i,",wsn=",wsn, ",success.") 162 | }(i) 163 | } 164 | 165 | //读取数据 166 | for i:= 1; i < 4; i++ { 167 | go func(i int){ 168 | rsn,d,_ := dataFile.Read() 169 | fmt.Println("Read i=", i,",rsn=",rsn,",data=",d, ",success.") 170 | }(i) 171 | } 172 | 173 | time.Sleep(10 * time.Second) 174 | } -------------------------------------------------------------------------------- /atomic/cas/cas.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync/atomic" 6 | ) 7 | 8 | var value int32 9 | 10 | func main() { 11 | fmt.Println("======old value=======") 12 | fmt.Println(value) 13 | fmt.Println("======CAS value=======") 14 | addValue(3) 15 | fmt.Println(value) 16 | fmt.Println("======Store value=======") 17 | atomic.StoreInt32(&value, 10) 18 | fmt.Println(value) 19 | } 20 | 21 | //不断地尝试原子地更新value的值,直到操作成功为止 22 | func addValue(delta int32){ 23 | //在被操作值被频繁变更的情况下,CAS操作并不那么容易成功 24 | //so 不得不利用for循环以进行多次尝试 25 | for { 26 | //v := value 27 | //在进行读取value的操作的过程中,其他对此值的读写操作是可以被同时进行的,那么这个读操作很可能会读取到一个只被修改了一半的数据. 28 | //因此我们要使用载入 29 | v := atomic.LoadInt32(&value) 30 | if atomic.CompareAndSwapInt32(&value, v, (v + delta)){ 31 | //在函数的结果值为true时,退出循环 32 | break 33 | } 34 | //操作失败的缘由总会是value的旧值已不与v的值相等了. 35 | //CAS操作虽然不会让某个Goroutine阻塞在某条语句上,但是仍可能会使流产的执行暂时停一下,不过时间大都极其短暂. 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /bytes/bufferRead.go: -------------------------------------------------------------------------------- 1 | // Go 之 bytes.buffer Read 2 | // 3 | // Copyright (c) 2015 - Batu <1235355@qq.com> 4 | // 5 | package main 6 | import ( 7 | "bytes" 8 | "fmt" 9 | "os" 10 | ) 11 | 12 | func main(){ 13 | fmt.Println("=======Read=======") 14 | Read() 15 | fmt.Println("=======ReadByte===") 16 | ReadByte() 17 | fmt.Println("=======ReadRune===") 18 | ReadRune() 19 | fmt.Println("=======ReadBytes==") 20 | ReadBytes() 21 | fmt.Println("=======ReadFrom===") 22 | ReadFrom() 23 | fmt.Println("=======Reset======") 24 | Reset() 25 | } 26 | 27 | func Read(){ 28 | bufs := bytes.NewBufferString("Learning swift.") 29 | fmt.Println(bufs.String()) 30 | 31 | //声明一个空的slice,容量为8 32 | l := make([]byte, 8) 33 | //把bufs的内容读入到l内,因为l容量为8,所以只读了8个过来 34 | bufs.Read(l) 35 | fmt.Println("::bufs缓冲器内容::") 36 | fmt.Println(bufs.String()) 37 | //空的l被写入了8个字符,所以为 Learning 38 | fmt.Println("::l的slice内容::") 39 | fmt.Println(string(l)) 40 | //把bufs的内容读入到l内,原来的l的内容被覆盖了 41 | bufs.Read(l) 42 | fmt.Println("::bufs缓冲器被第二次读取后剩余的内容::") 43 | fmt.Println(bufs.String()) 44 | fmt.Println("::l的slice内容被覆盖,由于bufs只有7个了,因此最后一个g被留下来了::") 45 | fmt.Println(string(l)) 46 | 47 | } 48 | 49 | func ReadByte(){ 50 | bufs := bytes.NewBufferString("Learning swift.") 51 | fmt.Println(bufs.String()) 52 | //读取第一个byte,赋值给b 53 | b, _ := bufs.ReadByte() 54 | fmt.Println(bufs.String()) 55 | fmt.Println(string(b)) 56 | } 57 | 58 | func ReadRune(){ 59 | bufs := bytes.NewBufferString("学swift.") 60 | fmt.Println(bufs.String()) 61 | 62 | //读取第一个rune,赋值给r 63 | r,z,_ := bufs.ReadRune() 64 | //打印中文"学",缓冲器头部第一个被拿走 65 | fmt.Println(bufs.String()) 66 | //打印"学","学"作为utf8储存占3个byte 67 | fmt.Println("r=",string(r),",z=",z) 68 | 69 | } 70 | 71 | func ReadBytes(){ 72 | bufs := bytes.NewBufferString("现在开始 Learning swift.") 73 | fmt.Println(bufs.String()) 74 | 75 | var delim byte = 'L' 76 | line, _ := bufs.ReadBytes(delim) 77 | fmt.Println(bufs.String()) 78 | fmt.Println(string(line)) 79 | } 80 | 81 | func ReadFrom(){ 82 | //test.txt 内容是 "未来" 83 | file, _ := os.Open("learngo/bytes/text.txt") 84 | buf := bytes.NewBufferString("Learning swift.") 85 | buf.ReadFrom(file) //将text.txt内容追加到缓冲器的尾部 86 | fmt.Println(buf.String()) 87 | } 88 | 89 | func Reset(){ 90 | bufs := bytes.NewBufferString("现在开始 Learning swift.") 91 | fmt.Println(bufs.String()) 92 | 93 | bufs.Reset() 94 | fmt.Println("::已经清空了bufs的缓冲内容::") 95 | fmt.Println(bufs.String()) 96 | } -------------------------------------------------------------------------------- /bytes/bufferWrite.go: -------------------------------------------------------------------------------- 1 | // Go 之 bytes.buffer Write 2 | // 3 | // Copyright (c) 2015 - Batu <1235355@qq.com> 4 | // 5 | package main 6 | 7 | import ( 8 | "bytes" 9 | "encoding/binary" 10 | "fmt" 11 | ) 12 | 13 | func main() { 14 | //newBuffer 整形转换成字节 15 | var n int = 10000 16 | intToBytes := IntToBytes(n) 17 | fmt.Println("==========int to bytes========") 18 | fmt.Println(intToBytes) 19 | //NewBufferString 20 | TestBufferString() 21 | //write 22 | BufferWrite() 23 | //WriteString 24 | BufferWriteString() 25 | //WriteByte 26 | BufferWriteByte() 27 | //WriteRune 28 | BufferWriteRune() 29 | 30 | } 31 | 32 | 33 | func IntToBytes(n int) []byte { 34 | x := int32(n) 35 | //创建一个内容是[]byte的slice的缓冲器 36 | //与bytes.NewBufferString("")等效 37 | bytesBuffer := bytes.NewBuffer([]byte{}) 38 | binary.Write(bytesBuffer, binary.BigEndian, x) 39 | return bytesBuffer.Bytes() 40 | } 41 | 42 | func TestBufferString(){ 43 | buf1:=bytes.NewBufferString("swift") 44 | buf2:=bytes.NewBuffer([]byte("swift")) 45 | buf3:=bytes.NewBuffer([]byte{'s','w','i','f','t'}) 46 | fmt.Println("===========以下buf1,buf2,buf3等效=========") 47 | fmt.Println("buf1:", buf1) 48 | fmt.Println("buf2:", buf2) 49 | fmt.Println("buf3:", buf3) 50 | fmt.Println("===========以下创建空的缓冲器等效=========") 51 | buf4:=bytes.NewBufferString("") 52 | buf5:=bytes.NewBuffer([]byte{}) 53 | fmt.Println("buf4:", buf4) 54 | fmt.Println("buf5:", buf5) 55 | } 56 | 57 | func BufferWrite(){ 58 | fmt.Println("===========以下通过Write把swift写入Learning缓冲器尾部=========") 59 | newBytes := []byte("swift") 60 | //创建一个内容Learning的缓冲器 61 | buf := bytes.NewBuffer([]byte("Learning")) 62 | //打印为Learning 63 | fmt.Println(buf.String()) 64 | //将newBytes这个slice写到buf的尾部 65 | buf.Write(newBytes) 66 | fmt.Println(buf.String()) 67 | } 68 | 69 | func BufferWriteString(){ 70 | fmt.Println("===========以下通过Write把swift写入Learning缓冲器尾部=========") 71 | newString := "swift" 72 | //创建一个string内容Learning的缓冲器 73 | buf := bytes.NewBufferString("Learning") 74 | //打印为Learning 75 | fmt.Println(buf.String()) 76 | //将newString这个string写到buf的尾部 77 | buf.WriteString(newString) 78 | fmt.Println(buf.String()) 79 | } 80 | 81 | func BufferWriteByte(){ 82 | fmt.Println("===========以下通过WriteByte把swift写入Learning缓冲器尾部=========") 83 | var newByte byte = '!' 84 | //创建一个string内容Learning的缓冲器 85 | buf := bytes.NewBufferString("Learning") 86 | //打印为Learning 87 | fmt.Println(buf.String()) 88 | //将newString这个string写到buf的尾部 89 | buf.WriteByte(newByte) 90 | fmt.Println(buf.String()) 91 | } 92 | 93 | func BufferWriteRune(){ 94 | fmt.Println("===========以下通过WriteRune把\"好\"写入Learning缓冲器尾部=========") 95 | var newRune = '好' 96 | //创建一个string内容Learning的缓冲器 97 | buf := bytes.NewBufferString("Learning") 98 | //打印为Learning 99 | fmt.Println(buf.String()) 100 | //将newString这个string写到buf的尾部 101 | buf.WriteRune(newRune) 102 | fmt.Println(buf.String()) 103 | } -------------------------------------------------------------------------------- /bytes/text.txt: -------------------------------------------------------------------------------- 1 | 未来 -------------------------------------------------------------------------------- /format/sprintf.go: -------------------------------------------------------------------------------- 1 | // Go 之 字符串格式化 2 | // 3 | // Copyright (c) 2015 - Batu <1235355@qq.com> 4 | // 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | ) 10 | 11 | type point struct { 12 | x, y int 13 | } 14 | 15 | func main(){ 16 | // 格式化整型,使用`%d`是一种 17 | // 标准的以十进制来输出整型的方式 18 | // 有符号十进制整数(int)(%ld、%Ld:长整型数据(long),%hd:输出短整形。) 19 | fmt.Println("=====%d,输出十进制====") 20 | fmt.Printf("%d\n", 110) 21 | 22 | // 输出整型的二进制表示方式 23 | fmt.Println("=====%b,输出二进制====") 24 | fmt.Printf("%b\n", 110) 25 | 26 | // 输出整型数值所对应的字符(char):一个字节,占8位 27 | // 可参考 ASCII 28 | fmt.Println("=====%c,输出一个值的字符(char)====") 29 | fmt.Printf("%c\n",97) 30 | 31 | // 输出一个值的十六进制,每个字符串的字节用两个字符输出 32 | fmt.Println("=====%x,输出一个值的十六进制,每个字符串的字节用两个字符输出====") 33 | fmt.Printf("0x%x\n", 10) 34 | fmt.Printf("%x\n", "abc") 35 | 36 | // 输出浮点型数值 37 | fmt.Println("=====%f,输出浮点型数值====") 38 | fmt.Printf("%f\n", 27.89) 39 | 40 | // 输出基本的字符串 41 | fmt.Println("=====%s,输出基本字符串====") 42 | fmt.Printf("%s-%s-%s\n","I","am","batu") 43 | 44 | // 输出带双引号的字符串 45 | fmt.Println("=====%q,输出带双引号的字符串====") 46 | fmt.Printf("%q\n","string") 47 | 48 | 49 | 50 | // Go提供了几种打印格式,用来格式化一般的Go值 51 | p := point{1, 2} 52 | 53 | fmt.Println("=====%p,输出一个指针的值====") 54 | fmt.Printf("%p\n", &p) 55 | fmt.Println("=====%v,输出结构体的对象值====") 56 | fmt.Printf("%v\n", p) 57 | // 如果所格式化的值是一个结构体对象,那么`%+v`的格式化输出 58 | fmt.Println("=====%+v,输出结构体的成员名称和值====") 59 | fmt.Printf("%+v\n", p) 60 | fmt.Println("=====%#v,输出一个值的Go语法表示方式====") 61 | fmt.Printf("%#v\n",p) 62 | fmt.Println("=====%T,输出一个值的数据类型====") 63 | fmt.Printf("%T\n",p) 64 | 65 | // 当输出数字的时候,经常需要去控制输出的宽度和精度。 66 | // 可以使用一个位于%后面的数字来控制输出的宽度,默认情况下输出是右对齐的,左边加上空格 67 | fmt.Println("=====控制输出的宽度和精度====") 68 | fmt.Printf("|%5d|%5d|\n", 12, 345) 69 | fmt.Println("=====输出宽度,同时指定浮点数====") 70 | fmt.Printf("|%5.2f|%5.2f|\n", 1.2, 3.45) 71 | fmt.Println("=====左对齐====") 72 | fmt.Printf("|%-5.2f|%-5.2f|\n", 1.2, 3.45) 73 | 74 | } -------------------------------------------------------------------------------- /mutex/main.go: -------------------------------------------------------------------------------- 1 | // test for Go 2 | // 3 | // Copyright (c) 2015 - Batu <1235355@qq.com> 4 | // 5 | // 创建一个文件存放数据,在同一时刻,可能会有多个Goroutine分别进行对此文件的写操作和读操作. 6 | // 每一次写操作都应该向这个文件写入若干个字节的数据,作为一个独立的数据块存在,这意味着写操作之间不能彼此干扰,写入的内容之间也不能出现穿插和混淆的情况 7 | // 每一次读操作都应该从这个文件中读取一个独立完整的数据块.它们读取的数据块不能重复,且需要按顺序读取. 8 | // 例如: 第一个读操作读取了数据块1,第二个操作就应该读取数据块2,第三个读操作则应该读取数据块3,以此类推 9 | // 对于这些读操作是否可以被同时执行,不做要求. 即使同时进行,也应该保持先后顺序. 10 | package main 11 | 12 | import ( 13 | "fmt" 14 | "sync" 15 | "time" 16 | "os" 17 | "errors" 18 | "io" 19 | ) 20 | 21 | //数据文件的接口类型 22 | type DataFile interface { 23 | // 读取一个数据块 24 | Read() (rsn int64, d Data, err error) 25 | // 写入一个数据块 26 | Write(d Data) (wsn int64, err error) 27 | // 获取最后读取的数据块的序列号 28 | Rsn() int64 29 | // 获取最后写入的数据块的序列号 30 | Wsn() int64 31 | // 获取数据块的长度 32 | DataLen() uint32 33 | } 34 | 35 | //数据类型 36 | type Data []byte 37 | 38 | //数据文件的实现类型 39 | type myDataFile struct { 40 | f *os.File //文件 41 | fmutex sync.RWMutex //被用于文件的读写锁 42 | woffset int64 // 写操作需要用到的偏移量 43 | roffset int64 // 读操作需要用到的偏移量 44 | wmutex sync.Mutex // 写操作需要用到的互斥锁 45 | rmutex sync.Mutex // 读操作需要用到的互斥锁 46 | dataLen uint32 //数据块长度 47 | } 48 | 49 | //初始化DataFile类型值的函数,返回一个DataFile类型的值 50 | func NewDataFile(path string, dataLen uint32) (DataFile, error){ 51 | f, err := os.OpenFile(path, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0666) 52 | //f,err := os.Create(path) 53 | if err != nil { 54 | fmt.Println("Fail to find", f, "cServer start Failed") 55 | return nil, err 56 | } 57 | 58 | if dataLen == 0 { 59 | return nil, errors.New("Invalid data length!") 60 | } 61 | 62 | df := &myDataFile{ 63 | f : f, 64 | dataLen:dataLen, 65 | } 66 | 67 | return df, nil 68 | } 69 | 70 | //获取并更新读偏移量,根据读偏移量从文件中读取一块数据,把该数据块封装成一个Data类型值并将其作为结果值返回 71 | 72 | func (df *myDataFile) Read() (rsn int64, d Data, err error){ 73 | // 读取并更新读偏移量 74 | var offset int64 75 | // 读互斥锁定 76 | df.rmutex.Lock() 77 | offset = df.roffset 78 | // 更改偏移量, 当前偏移量+数据块长度 79 | df.roffset += int64(df.dataLen) 80 | // 读互斥解锁 81 | df.rmutex.Unlock() 82 | 83 | //读取一个数据块,最后读取的数据块序列号 84 | rsn = offset / int64(df.dataLen) 85 | bytes := make([]byte, df.dataLen) 86 | for { 87 | //读写锁:读锁定 88 | df.fmutex.RLock() 89 | _, err = df.f.ReadAt(bytes, offset) 90 | if err != nil { 91 | //由于进行写操作的Goroutine比进行读操作的Goroutine少,所以过不了多久读偏移量roffset的值就会大于写偏移量woffset的值 92 | // 也就是说,读操作很快就没有数据块可读了,这种情况会让df.f.ReadAt方法返回的第二个结果值为代表的非nil且会与io.EOF相等的值 93 | // 因此不应该把EOF看成错误的边界情况 94 | // so 在读操作读完数据块,EOF时解锁读操作,并继续循环,尝试获取同一个数据块,直到获取成功为止. 95 | if err == io.EOF { 96 | //注意,如果在该for代码块被执行期间,一直让读写所fmutex处于读锁定状态,那么针对它的写操作将永远不会成功. 97 | //切相应的Goroutine也会被一直阻塞.因为它们是互斥的. 98 | // so 在每条return & continue 语句的前面加入一个针对该读写锁的读解锁操作 99 | df.fmutex.RUnlock() 100 | //注意,出现EOF时可能是很多意外情况,如文件被删除,文件损坏等 101 | //这里可以考虑把逻辑提交给上层处理. 102 | continue 103 | } 104 | } 105 | break 106 | } 107 | d = bytes 108 | df.fmutex.RUnlock() 109 | return 110 | } 111 | 112 | func (df *myDataFile) Write(d Data) (wsn int64, err error){ 113 | //读取并更新写的偏移量 114 | var offset int64 115 | df.wmutex.Lock() 116 | offset = df.woffset 117 | df.woffset += int64(df.dataLen) 118 | df.wmutex.Unlock() 119 | 120 | //写入一个数据块,最后写入数据块的序号 121 | wsn = offset / int64(df.dataLen) 122 | var bytes []byte 123 | if len(d) > int(df.dataLen){ 124 | bytes = d[0:df.dataLen] 125 | }else{ 126 | bytes = d 127 | } 128 | df.fmutex.Lock() 129 | df.fmutex.Unlock() 130 | _, err = df.f.Write(bytes) 131 | 132 | return 133 | } 134 | 135 | func (df *myDataFile) Rsn() int64{ 136 | df.rmutex.Lock() 137 | defer df.rmutex.Unlock() 138 | return df.roffset / int64(df.dataLen) 139 | } 140 | 141 | func (df *myDataFile) Wsn() int64{ 142 | df.wmutex.Lock() 143 | defer df.wmutex.Unlock() 144 | return df.woffset / int64(df.dataLen) 145 | } 146 | 147 | func (df *myDataFile) DataLen() uint32 { 148 | return df.dataLen 149 | } 150 | 151 | func main(){ 152 | //简单测试下结果 153 | var dataFile DataFile 154 | dataFile,_ = NewDataFile("./mutex_2015_1.dat", 10) 155 | 156 | var d=map[int]Data{ 157 | 1:[]byte("batu_test1"), 158 | 2:[]byte("batu_test2"), 159 | 3:[]byte("test1_batu"), 160 | } 161 | 162 | //写入数据 163 | for i:= 1; i < 4; i++ { 164 | go func(i int){ 165 | wsn,_ := dataFile.Write(d[i]) 166 | fmt.Println("write i=", i,",wsn=",wsn, ",success.") 167 | }(i) 168 | } 169 | 170 | //读取数据 171 | for i:= 1; i < 4; i++ { 172 | go func(i int){ 173 | rsn,d,_ := dataFile.Read() 174 | fmt.Println("Read i=", i,",rsn=",rsn,",data=",d, ",success.") 175 | }(i) 176 | } 177 | 178 | time.Sleep(10 * time.Second) 179 | } -------------------------------------------------------------------------------- /mutex_cond/cond.go: -------------------------------------------------------------------------------- 1 | // Go 之 条件变量 & 锁使用 2 | // 3 | // Copyright (c) 2015 - Batu <1235355@qq.com> 4 | // 5 | // 创建一个文件存放数据,在同一时刻,可能会有多个Goroutine分别进行对此文件的写操作和读操作. 6 | // 每一次写操作都应该向这个文件写入若干个字节的数据,作为一个独立的数据块存在,这意味着写操作之间不能彼此干扰,写入的内容之间也不能出现穿插和混淆的情况 7 | // 每一次读操作都应该从这个文件中读取一个独立完整的数据块.它们读取的数据块不能重复,且需要按顺序读取. 8 | // 例如: 第一个读操作读取了数据块1,第二个操作就应该读取数据块2,第三个读操作则应该读取数据块3,以此类推 9 | // 对于这些读操作是否可以被同时执行,不做要求. 即使同时进行,也应该保持先后顺序. 10 | package main 11 | 12 | import ( 13 | "fmt" 14 | "sync" 15 | "time" 16 | "os" 17 | "errors" 18 | "io" 19 | ) 20 | 21 | //数据文件的接口类型 22 | type DataFile interface { 23 | // 读取一个数据块 24 | Read() (rsn int64, d Data, err error) 25 | // 写入一个数据块 26 | Write(d Data) (wsn int64, err error) 27 | // 获取最后读取的数据块的序列号 28 | Rsn() int64 29 | // 获取最后写入的数据块的序列号 30 | Wsn() int64 31 | // 获取数据块的长度 32 | DataLen() uint32 33 | } 34 | 35 | //数据类型 36 | type Data []byte 37 | 38 | //数据文件的实现类型 39 | type myDataFile struct { 40 | f *os.File //文件 41 | fmutex sync.RWMutex //被用于文件的读写锁 42 | rcond *sync.Cond //读操作需要用到的条件变量 43 | woffset int64 // 写操作需要用到的偏移量 44 | roffset int64 // 读操作需要用到的偏移量 45 | wmutex sync.Mutex // 写操作需要用到的互斥锁 46 | rmutex sync.Mutex // 读操作需要用到的互斥锁 47 | dataLen uint32 //数据块长度 48 | } 49 | 50 | //初始化DataFile类型值的函数,返回一个DataFile类型的值 51 | func NewDataFile(path string, dataLen uint32) (DataFile, error){ 52 | //f, err := os.OpenFile(path, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0666) 53 | f,err := os.Create(path) 54 | if err != nil { 55 | fmt.Println("Fail to find", f, "cServer start Failed") 56 | return nil, err 57 | } 58 | 59 | if dataLen == 0 { 60 | return nil, errors.New("Invalid data length!") 61 | } 62 | 63 | df := &myDataFile{ 64 | f : f, 65 | dataLen:dataLen, 66 | } 67 | //创建一个可用的条件变量(初始化),返回一个*sync.Cond类型的结果值,我们就可以调用该值拥有的三个方法Wait,Signal,Broadcast 68 | df.rcond = sync.NewCond(df.fmutex.RLocker()) 69 | return df, nil 70 | } 71 | 72 | //获取并更新读偏移量,根据读偏移量从文件中读取一块数据,把该数据块封装成一个Data类型值并将其作为结果值返回 73 | 74 | func (df *myDataFile) Read() (rsn int64, d Data, err error){ 75 | // 读取并更新读偏移量 76 | var offset int64 77 | // 读互斥锁定 78 | df.rmutex.Lock() 79 | offset = df.roffset 80 | // 更改偏移量, 当前偏移量+数据块长度 81 | df.roffset += int64(df.dataLen) 82 | // 读互斥解锁 83 | df.rmutex.Unlock() 84 | 85 | //读取一个数据块,最后读取的数据块序列号 86 | rsn = offset / int64(df.dataLen) 87 | bytes := make([]byte, df.dataLen) 88 | //读写锁:读锁定 89 | df.fmutex.RLock() 90 | defer df.fmutex.RUnlock() 91 | 92 | for { 93 | _, err = df.f.ReadAt(bytes, offset) 94 | if err != nil { 95 | if err == io.EOF { 96 | //暂时放弃fmutex的 读锁,并等待通知的到来 97 | df.rcond.Wait() 98 | continue 99 | } 100 | } 101 | break 102 | } 103 | d = bytes 104 | return 105 | } 106 | 107 | func (df *myDataFile) Write(d Data) (wsn int64, err error){ 108 | //读取并更新写的偏移量 109 | var offset int64 110 | df.wmutex.Lock() 111 | offset = df.woffset 112 | df.woffset += int64(df.dataLen) 113 | df.wmutex.Unlock() 114 | 115 | //写入一个数据块,最后写入数据块的序号 116 | wsn = offset / int64(df.dataLen) 117 | var bytes []byte 118 | if len(d) > int(df.dataLen){ 119 | bytes = d[0:df.dataLen] 120 | }else{ 121 | bytes = d 122 | } 123 | df.fmutex.Lock() 124 | defer df.fmutex.Unlock() 125 | _, err = df.f.Write(bytes) 126 | //发送通知 127 | df.rcond.Signal() 128 | return 129 | } 130 | 131 | func (df *myDataFile) Rsn() int64{ 132 | df.rmutex.Lock() 133 | defer df.rmutex.Unlock() 134 | return df.roffset / int64(df.dataLen) 135 | } 136 | 137 | func (df *myDataFile) Wsn() int64{ 138 | df.wmutex.Lock() 139 | defer df.wmutex.Unlock() 140 | return df.woffset / int64(df.dataLen) 141 | } 142 | 143 | func (df *myDataFile) DataLen() uint32 { 144 | return df.dataLen 145 | } 146 | 147 | func main(){ 148 | //简单测试下结果 149 | var dataFile DataFile 150 | dataFile,_ = NewDataFile("./mutex_2015_1.dat", 10) 151 | 152 | var d=map[int]Data{ 153 | 1:[]byte("batu_test1"), 154 | 2:[]byte("batu_tstt2"), 155 | 3:[]byte("batu_test3"), 156 | } 157 | 158 | //写入数据 159 | for i:= 1; i < 4; i++ { 160 | go func(i int){ 161 | wsn,_ := dataFile.Write(d[i]) 162 | fmt.Println("write i=", i,",wsn=",wsn, ",success.") 163 | }(i) 164 | } 165 | 166 | //读取数据 167 | for i:= 1; i < 4; i++ { 168 | go func(i int){ 169 | rsn,d,_ := dataFile.Read() 170 | fmt.Println("Read i=", i,",rsn=",rsn,",data=",d, ",success.") 171 | }(i) 172 | } 173 | 174 | time.Sleep(10 * time.Second) 175 | } -------------------------------------------------------------------------------- /reflect/reflect.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "reflect" 5 | "fmt" 6 | ) 7 | 8 | type ControllerInterface interface { 9 | Init(action string, method string) 10 | } 11 | 12 | type Controller struct { 13 | Action string 14 | Method string 15 | Tag string `json:"tag"` 16 | } 17 | 18 | func (c *Controller) Init(action string, method string){ 19 | c.Action = action 20 | c.Method = method 21 | 22 | fmt.Println("Init() is run.") 23 | fmt.Println("c:",c) 24 | } 25 | 26 | func (c *Controller) Test(){ 27 | fmt.Println("Test() is run.") 28 | } 29 | 30 | 31 | func main(){ 32 | //初始化 33 | runController := &Controller{ 34 | Action:"Run1", 35 | Method:"GET", 36 | } 37 | 38 | //Controller实现了ControllerInterface方法,因此它就实现了ControllerInterface接口 39 | var i ControllerInterface 40 | i = runController 41 | 42 | // 得到实际的值,通过v我们获取存储在里面的值,还可以去改变值 43 | v := reflect.ValueOf(i) 44 | fmt.Println("value:",v) 45 | 46 | // 得到类型的元数据,通过t我们能获取类型定义里面的所有元素 47 | t := reflect.TypeOf(i) 48 | fmt.Println("type:",t) 49 | 50 | // 转化为reflect对象之后我们就可以进行一些操作了,也就是将reflect对象转化成相应的值,例如 51 | controllerType := t.Elem() 52 | tag := controllerType.Field(2).Tag 53 | fmt.Println("Tag:", tag) 54 | 55 | // 获取i所指向的对象的类型(reflect.Value) 56 | controllerValue := v.Elem() 57 | fmt.Println("controllerType(reflect.Value):",controllerType) 58 | //获取存储在第一个字段里面的值 59 | fmt.Println("Action:", controllerValue.Field(0).String()) 60 | 61 | method, _ := t.MethodByName("Init") 62 | fmt.Println(method) 63 | 64 | vMethod := v.MethodByName("Init") 65 | fmt.Println(vMethod) 66 | 67 | // 有输入参数的方法调用 68 | // 构造输入参数 69 | args1 := []reflect.Value{reflect.ValueOf("Run2"),reflect.ValueOf("POST")} 70 | // 通过v进行调用 71 | v.MethodByName("Init").Call(args1) 72 | 73 | // 无输入参数的方法调用 74 | // 构造zero value 75 | args2 := make([]reflect.Value, 0) 76 | // 通过v进行调用 77 | v.MethodByName("Test").Call(args2) 78 | 79 | } 80 | -------------------------------------------------------------------------------- /sokect/protocol/protocol.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | import ( 3 | "bytes" 4 | "encoding/binary" 5 | ) 6 | 7 | const ( 8 | //消息头内容 9 | TCPHeader = "atc.wiki" 10 | //消息头长度 11 | TCPHeaderLength = 8 12 | //发送内容长度 13 | TCPSaveDataLength = 4 14 | ) 15 | 16 | //封包 17 | func Packet(message []byte) []byte { 18 | return append(append([]byte(TCPHeader),IntToBytes(len(message))...), message...) 19 | } 20 | 21 | //解包 22 | func Unpack(buf []byte, readerChan chan []byte) []byte{ 23 | length := len(buf) 24 | 25 | var i int 26 | for i = 0; i < length; i ++ { 27 | //是否为一个完整消息头 28 | if length < i + TCPHeaderLength + TCPSaveDataLength { 29 | break 30 | } 31 | 32 | if string(buf[i:i + TCPHeaderLength]) == TCPHeader { 33 | //消息内容长度 34 | messageLength := BytesToInt(buf[i+TCPHeaderLength : i + TCPHeaderLength + TCPSaveDataLength]) 35 | //是否为一个完整消息实体 36 | if length < i + TCPHeaderLength + TCPSaveDataLength + messageLength { 37 | break 38 | } 39 | //截取一个完整消息内容 40 | data := buf[i + TCPHeaderLength + TCPSaveDataLength : i + TCPHeaderLength + TCPSaveDataLength + messageLength] 41 | //发送给管道 42 | readerChan <- data 43 | 44 | //从下一个消息头读取 45 | i += TCPHeaderLength + TCPSaveDataLength + messageLength - 1 46 | } 47 | } 48 | 49 | //读完后初始化截断缓冲器 50 | if i == length { 51 | return make([]byte,0) 52 | } 53 | 54 | //返回截断缓冲内容,下次读取时继续 55 | return buf[i:] 56 | } 57 | 58 | 59 | //整形转换成字节 60 | func IntToBytes(n int) []byte { 61 | x := int32(n) 62 | 63 | bytesBuffer := bytes.NewBuffer([]byte{}) 64 | binary.Write(bytesBuffer, binary.BigEndian, x) 65 | return bytesBuffer.Bytes() 66 | } 67 | 68 | //字节转换成整形 69 | func BytesToInt(b []byte) int { 70 | bytesBuffer := bytes.NewBuffer(b) 71 | 72 | var x int32 73 | binary.Read(bytesBuffer, binary.BigEndian, &x) 74 | 75 | return int(x) 76 | } -------------------------------------------------------------------------------- /sokect/sokect.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "./tcp" 5 | "time" 6 | ) 7 | 8 | func main(){ 9 | runChan := make(chan []byte, 1) 10 | go tcp.RunService() 11 | 12 | time.Sleep(1 * time.Millisecond) 13 | 14 | go tcp.RunClient() 15 | <- runChan 16 | } 17 | -------------------------------------------------------------------------------- /sokect/tcp/client.go: -------------------------------------------------------------------------------- 1 | package tcp 2 | import ( 3 | "net" 4 | "fmt" 5 | "time" 6 | "../protocol" 7 | ) 8 | 9 | 10 | func write(conn net.Conn){ 11 | for i := 0; i < 100; i ++ { 12 | words := "{\"Id\":1,\"Name\":\"golang\",\"Message\":\"messagessss\"}" 13 | _,err := conn.Write(protocol.Packet([]byte(words))) 14 | CheckErr(err) 15 | } 16 | fmt.Println("write end.") 17 | } 18 | 19 | func RunClient(){ 20 | addr := "127.0.0.1:9999" 21 | tcpAdd, err := net.ResolveTCPAddr("tcp4", addr) 22 | CheckErr(err) 23 | 24 | conn, err := net.DialTCP("tcp", nil, tcpAdd) 25 | CheckErr(err) 26 | 27 | defer conn.Close() 28 | fmt.Println("connect success.") 29 | go write(conn) 30 | for { 31 | time.Sleep(1 * 1e9) 32 | } 33 | } 34 | 35 | 36 | -------------------------------------------------------------------------------- /sokect/tcp/server.go: -------------------------------------------------------------------------------- 1 | package tcp 2 | import ( 3 | "net" 4 | "fmt" 5 | "os" 6 | "../protocol" 7 | ) 8 | 9 | func RunService(){ 10 | netListen, err := net.Listen("tcp", ":9999") 11 | CheckErr(err) 12 | 13 | defer netListen.Close() 14 | 15 | fmt.Println("Waiting for clients...") 16 | for{ 17 | conn, err := netListen.Accept() 18 | if err != nil { 19 | continue 20 | } 21 | fmt.Println(conn.RemoteAddr().String(), " tcp connet success.") 22 | go handlerConnection(conn) 23 | } 24 | } 25 | 26 | func handlerConnection(conn net.Conn){ 27 | //声明临时缓冲区,存储被截断的数据 28 | tmpBuf := make([]byte,0) 29 | 30 | //声明管道,接收解包的数据 31 | readerChan := make(chan []byte, 16) 32 | go reader(readerChan) 33 | 34 | buf := make([]byte, 1024) 35 | for { 36 | n , err := conn.Read(buf) 37 | if err != nil { 38 | fmt.Println(conn.RemoteAddr().String(), " connection error: ", err) 39 | return 40 | } 41 | fmt.Println(conn.RemoteAddr().String(), " receive data, length:",n) 42 | // fmt.Println(conn.RemoteAddr().String(), "receive data:", buf[:n]) 43 | // fmt.Println(conn.RemoteAddr().String(), "receive data string:", string(buf[:n])) 44 | 45 | tmpBuf = protocol.Unpack(append(tmpBuf, buf[:n]...), readerChan) 46 | } 47 | } 48 | 49 | func reader(readerChan chan []byte){ 50 | for { 51 | select { 52 | case data := <- readerChan: 53 | fmt.Println(string(data)) 54 | } 55 | } 56 | } 57 | 58 | func CheckErr(err error){ 59 | if err != nil { 60 | fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error()) 61 | os.Exit(1) 62 | } 63 | } --------------------------------------------------------------------------------