1. // main
  2. package main
  3.  
  4. import (
  5. "fmt"
  6. "runtime"
  7. "sync"
  8. )
  9.  
  10. func main() {
  11. fmt.Println("Hello World!")
  12. runtime.GOMAXPROCS()
  13. var wg sync.WaitGroup
  14. wg.Add()
  15. i :=
  16. fmt.Println("Start Goroutines")
  17.  
  18. go func() {
  19. defer wg.Done()
  20. //共享变量 i wg
  21. fmt.Println(i)
  22. for count := ; count < ; count++ {
  23. for char := 'a'; char < 'a'+; char++ {
  24. fmt.Printf("%c ", char)
  25. }
  26. }
  27. }()
  28.  
  29. go func() {
  30. defer wg.Done()
  31. fmt.Println(i)
  32. for count := ; count < ; count++ {
  33. for char := 'A'; char < 'A'+; char++ {
  34. fmt.Printf("%c ", char)
  35. }
  36. }
  37. }()
  38.  
  39. fmt.Println("Waiting to Finish")
  40. wg.Wait()
  41.  
  42. fmt.Println("\nTerminating Program")
  43. }

go 协程练习

接口练习

  1. // Sample program to show what happens when the outer and inner
  2. // type implement the same interface.
  3. package main
  4.  
  5. import (
  6. "fmt"
  7. )
  8.  
  9. // notifier is an interface that defined notification
  10. // type behavior.
  11. type notifier interface {
  12. notify()
  13. }
  14.  
  15. // user defines a user in the program.
  16. type user struct {
  17. name string
  18. email string
  19. }
  20.  
  21. // notify implements a method that can be called via
  22. // a value of type user.
  23. func (u *user) notify() {
  24. fmt.Printf("Sending user email to %s<%s>\n",
  25. u.name,
  26. u.email)
  27. }
  28.  
  29. // admin represents an admin user with privileges.
  30. type admin struct {
  31. user
  32. level string
  33. }
  34.  
  35. // notify implements a method that can be called via
  36. // a value of type Admin.
  37. func (a *admin) notify() {
  38. fmt.Printf("Sending admin email to %s<%s>\n",
  39. a.name,
  40. a.email)
  41. }
  42.  
  43. // main is the entry point for the application.
  44. func main() {
  45. // Create an admin user.
  46. ad := admin{
  47. user: user{
  48. name: "john smith",
  49. email: "john@yahoo.com",
  50. },
  51. level: "super",
  52. }
  53.  
  54. // Send the admin user a notification.
  55. // The embedded inner type's implementation of the
  56. // interface is NOT "promoted" to the outer type.
  57. sendNotification(&ad)
  58.  
  59. // We can access the inner type's method directly.
  60. ad.user.notify()
  61.  
  62. // The inner type's method is NOT promoted.
  63. ad.notify()
  64. }
  65.  
  66. // sendNotification accepts values that implement the notifier
  67. // interface and sends notifications.
  68. func sendNotification(n notifier) {
  69. n.notify()
  70. }

work代码注释 《go语言编程实战》

  1. package work
  2.  
  3. import "sync"
  4.  
  5. //接口
  6. type Worker interface {
  7. Task()
  8. }
  9.  
  10. //pool结构体
  11. type Pool struct {
  12. work chan Worker
  13. wg sync.WaitGroup
  14. }
  15.  
  16. //new函数 返回 pool指针
  17. func New(maxGorountines int) *Pool {
  18. p := Pool{
  19. work: make(chan Worker),
  20. }
  21. //wg添加wait数量
  22. p.wg.Add(maxGorountines)
  23. for i := ; i < maxGorountines; i++ {
  24. go func() {
  25. //执行POOL内的任务 完成后wg执行done
  26. for w := range p.work {
  27. w.Task()
  28. }
  29. p.wg.Done()
  30. }()
  31. }
  32.  
  33. return &p
  34. }
  35.  
  36. //将任务放入POOL
  37. func (p *Pool) Run(w Worker) {
  38. p.work <- w
  39. }
  40.  
  41. //关闭POOL
  42. func (p *Pool) Shutdown() {
  43. close(p.work)
  44. p.wg.Wait()
  45. }
  1. // main
  2. package main
  3.  
  4. import (
  5. "fmt"
  6. "log"
  7. "sync"
  8. "time"
  9. "work"
  10. )
  11.  
  12. var names = []string{
  13. "steve",
  14. "bob",
  15. "mary",
  16. "therese",
  17. "jason",
  18. }
  19.  
  20. type namePrinter struct {
  21. name string
  22. }
  23.  
  24. func (m *namePrinter) Task() {
  25. log.Println(m.name)
  26. time.Sleep(time.Second)
  27. }
  28.  
  29. func main() {
  30. fmt.Println("Hello World!")
  31. p := work.New()
  32.  
  33. var wg sync.WaitGroup
  34. wg.Add( * len(names))
  35.  
  36. for i := ; i < ; i++ {
  37. for _, name := range names {
  38. np := namePrinter{
  39. name: name,
  40. }
  41. go func() {
  42. p.Run(&np)
  43. wg.Done()
  44. }()
  45. }
  46. }
  47. wg.Wait()
  48. p.Shutdown()
  49. }

runner代码注释 《go语言编程实战》

  1. // runner
  2. package runner
  3.  
  4. import (
  5. "errors"
  6. "fmt"
  7. "os"
  8. "os/signal"
  9. "time"
  10. )
  11.  
  12. //runner结构体
  13. type Runner struct {
  14. interrupt chan os.Signal
  15. complete chan error
  16. timeout <-chan time.Time
  17. tasks []func(int)
  18. }
  19.  
  20. //错误变量1
  21. var Errtimeout = errors.New("received timeout")
  22. //错误变量2
  23. var ErrInterrupt = errors.New("received interrupt")
  24.  
  25. //runner的new函数
  26. func New(d time.Duration) *Runner {
  27. return &Runner{
  28. interrupt: make(chan os.Signal, ),
  29. complete: make(chan error),
  30. timeout: time.After(d),
  31. }
  32. }
  33.  
  34. //func(int)加入 runner
  35. func (r *Runner) Add(tasks ...func(int)) {
  36. r.tasks = append(r.tasks, tasks...)
  37. }
  38.  
  39. //goroutine执行 结果超时或者错误 成功
  40. func (r *Runner) Start() error {
  41. signal.Notify(r.interrupt, os.Interrupt)
  42.  
  43. go func() {
  44. r.complete <- r.run()
  45. }()
  46.  
  47. select {
  48. case err := <-r.complete:
  49. return err
  50. case <-r.timeout:
  51. return Errtimeout
  52. }
  53. }
  54.  
  55. //run函数 遍历函数数组
  56. //若发生错误中断则返回 中断错误
  57. func (r *Runner) run() error {
  58. for id, task := range r.tasks {
  59. if r.gotInterrupt() {
  60. return ErrInterrupt
  61. }
  62. task(id)
  63. }
  64. return nil
  65. }
  66.  
  67. //通过interrupt接受中断
  68. func (r *Runner) gotInterrupt() bool {
  69. select {
  70. case <-r.interrupt:
  71. signal.Stop(r.interrupt)
  72. return true
  73. default:
  74. return false
  75. }
  76. }
  77.  
  78. //无用main函数
  79. func main() {
  80. fmt.Println("Hello World!")
  81.  
  82. }
  1. // main
  2. package main
  3.  
  4. import (
  5. "fmt"
  6. "log"
  7. "os"
  8. "runner"
  9. "time"
  10. )
  11.  
  12. const timeout = * time.Second
  13.  
  14. func main() {
  15. fmt.Println("Hello World!")
  16. log.Println("Starting work.")
  17.  
  18. r := runner.New(timeout)
  19.  
  20. r.Add(createTask(), createTask(), createTask())
  21.  
  22. if err := r.Start(); err != nil {
  23. switch err {
  24. case runner.Errtimeout:
  25. log.Println("Terminating due to timeout")
  26. os.Exit()
  27. case runner.ErrInterrupt:
  28. log.Println("Terminating due to interrupt")
  29. os.Exit()
  30. }
  31. }
  32. log.Println("Process ended")
  33. }
  34.  
  35. func createTask() func(int) {
  36. return func(id int) {
  37. log.Printf("processor - Task #%d", id)
  38. time.Sleep(time.Duration(id) * time.Second)
  39. }
  40. }

go语言编程 代码修改

  1. package library
  2.  
  3. //music 记录
  4. type MusicEntry struct {
  5. Id string
  6. Name string
  7. Artist string
  8. Source string
  9. Type string
  10. }

musicentry

  1. package library
  2.  
  3. import "errors"
  4.  
  5. //音乐管理器 音乐记录数组
  6. type MusicManager struct {
  7. musics []MusicEntry
  8. }
  9.  
  10. //返回音乐管理器指针
  11. func NewMusicManager() *MusicManager {
  12. return &MusicManager{make([]MusicEntry, )}
  13. }
  14.  
  15. //返回音乐管理器 音乐数组的元素数
  16. func (m *MusicManager) Len() int {
  17. return len(m.musics)
  18. }
  19.  
  20. //输入索引 获取音乐记录指针
  21. func (m *MusicManager) Get(index int) (music *MusicEntry, err error) {
  22. if index < || index >= len(m.musics) {
  23. return nil, errors.New("Index out of range.")
  24. }
  25. return &m.musics[index], nil
  26. }
  27.  
  28. //根据名字字符串 查找音乐记录的指针
  29. func (m *MusicManager) Find(name string) *MusicEntry {
  30. if len(m.musics) == {
  31. return nil
  32. }
  33.  
  34. for _, m := range m.musics {
  35. if m.Name == name {
  36. return &m
  37. }
  38. }
  39. return nil
  40. }
  41.  
  42. //添加音乐记录 输入音乐记录指针
  43. func (m *MusicManager) Add(music *MusicEntry) {
  44.  
  45. m.musics = append(m.musics, *music)
  46. }
  47.  
  48. //输入索引 移除指定索引 返回音乐记录指针
  49. func (m *MusicManager) Remove(index int) *MusicEntry {
  50. if index < || index >= len(m.musics) {
  51. return nil
  52. }
  53.  
  54. removedMusic := &m.musics[index]
  55.  
  56. // Remove the found item from the slice.
  57. if index < len(m.musics)- { // Element between first and last
  58. m.musics = append(m.musics[:index-], m.musics[index+:]...)
  59. } else if index == { // empty it.
  60. m.musics = make([]MusicEntry, )
  61. } else { // The last element
  62. m.musics = m.musics[:index-]
  63. }
  64.  
  65. return removedMusic
  66. }
  67.  
  68. //输入名字字符串 移除符合的音乐记录 返回音乐记录指针
  69. func (m *MusicManager) RemoveByName(name string) *MusicEntry {
  70. if len(m.musics) == {
  71. return nil
  72. }
  73.  
  74. for i, v := range m.musics {
  75. if v.Name == name {
  76. return m.Remove(i)
  77. }
  78. }
  79. return nil
  80. }

manager

  1. package library
  2.  
  3. import "testing"
  4.  
  5. func TestOps(t *testing.T) {
  6. mm := NewMusicManager()
  7. if mm == nil {
  8. t.Error("NewMusicManager failed")
  9. }
  10.  
  11. if mm.Len() != {
  12. t.Error("NewMusicManager failed,not empty")
  13. }
  14.  
  15. m0 := &MusicEntry{"", "MyHeart", "Celion", "http://wwww", "pop"}
  16. mm.Add(m0)
  17.  
  18. if mm.Len() != {
  19. t.Error("MusicManager Add() failed")
  20. }
  21.  
  22. m := mm.Find(m0.Name)
  23. if m == nil {
  24. t.Error("MusicManager Find() failed")
  25. }
  26.  
  27. if m.Id != m0.Id || m.Name != m0.Name ||
  28. m.Artist != m0.Artist || m.Source != m0.Source ||
  29. m.Type != m0.Type {
  30. t.Error("MusicManager Find() failed.Found item mismatch")
  31. }
  32.  
  33. m, err := mm.Get()
  34. if m == nil || err != nil {
  35. t.Error("MusicManager Get() failed")
  36. }
  37.  
  38. m = mm.Remove()
  39. if m == nil || mm.Len() != {
  40. t.Error("MusicManager Remove() failed")
  41. }
  42.  
  43. }

manager_test

服务器 代码备份

  1. // main
  2. package main
  3.  
  4. import (
  5. //"crypto/cipher"
  6. //"bufio"
  7. "bytes"
  8. "crypto/aes"
  9. "encoding/binary"
  10. "errors"
  11. "fmt"
  12. "log"
  13. "net"
  14. )
  15.  
  16. var g_string string
  17.  
  18. type Header struct {
  19. flag byte
  20. packageLen int32
  21. }
  22.  
  23. //字节转换成整形
  24. func BytesToInt(b []byte) int {
  25. bytesBuffer := bytes.NewBuffer(b)
  26.  
  27. var x int32
  28. binary.Read(bytesBuffer, binary.LittleEndian, &x)
  29.  
  30. return int(x)
  31. }
  32.  
  33. func recvBuf(conn net.Conn, buf []byte) (int, error) {
  34. n, err := conn.Read(buf)
  35. return n, err
  36. }
  37.  
  38. func recvHeader(conn net.Conn) (int, error) {
  39. headerbuf := make([]byte, )
  40. //fmt.Println("before buf:", headerbuf)
  41.  
  42. n, err := recvBuf(conn, headerbuf)
  43. if err != nil || n != {
  44. fmt.Println("err:", err)
  45. return -, err
  46. }
  47. //fmt.Println("after buf:", headerbuf, " n:", n)
  48. if headerbuf[] != '|' {
  49. fmt.Println("err:flag error,exit!")
  50. return -, err
  51. }
  52. n = BytesToInt(headerbuf[:])
  53. return n, err
  54. }
  55.  
  56. func recvBody(conn net.Conn, n int) (int, error) {
  57. var err = errors.New(" closed")
  58. buf := make([]byte, n)
  59.  
  60. n, err = recvBuf(conn, buf)
  61. if err != nil || n <= {
  62. fmt.Println("err:", err)
  63. return -, err
  64. }
  65. //buf 解密
  66. mainecb(buf)
  67.  
  68. return n, err
  69. }
  70.  
  71. func handleConn(conn net.Conn) {
  72. fmt.Println("Enter func handleConn")
  73. defer conn.Close()
  74. who := conn.RemoteAddr().String()
  75. fmt.Println(who)
  76. for {
  77. n, err := recvHeader(conn)
  78. //fmt.Println("recvHeader n = ", n, " ", err)
  79. if n <= || err != nil {
  80. var ErrEOF = errors.New("EOF")
  81. if err == ErrEOF {
  82. fmt.Println("err eauql")
  83. }
  84. fmt.Println("err:recvHeader error,exit! ,err:", err)
  85. break
  86. }
  87. _, err = recvBody(conn, n)
  88. }
  89.  
  90. }
  91.  
  92. //===============================================
  93. //ecb
  94. //===============================================
  95. //AES ECB模式的加密解密
  96. type AesTool struct {
  97. //128 192 256位的其中一个 长度 对应分别是 16 24 32字节长度
  98. Key []byte
  99. BlockSize int
  100. }
  101.  
  102. func (this *AesTool) Decrypt(src []byte) ([]byte, error) {
  103. //key只能是 16 24 32长度
  104. block, err := aes.NewCipher([]byte(this.Key))
  105. if err != nil {
  106. return nil, err
  107. }
  108. //返回加密结果
  109. decryptData := make([]byte, len(src))
  110. //存储每次加密的数据
  111. tmpData := make([]byte, this.BlockSize)
  112.  
  113. //分组分块加密
  114. for index := ; index < len(src); index += this.BlockSize {
  115. block.Decrypt(tmpData, src[index:index+this.BlockSize])
  116. //copy(decryptData, tmpData)
  117. decryptData = mergeByteArray(decryptData, tmpData)
  118. }
  119. return this.PKCS5UnPadding(decryptData), nil
  120. }
  121.  
  122. func mergeByteArray(a []byte, b []byte) []byte {
  123. alen := len(a)
  124. blen := len(b)
  125.  
  126. z := make([]byte, alen+blen)
  127.  
  128. for i := ; i < alen; i++ {
  129. z[i] = a[i]
  130. }
  131. for i := ; i < blen; i++ {
  132. z[alen+i] = b[i]
  133. }
  134. return z
  135. }
  136.  
  137. //unpadding
  138. func (this *AesTool) unPadding(src []byte) []byte {
  139. for i := len(src) - ; ; i-- {
  140. if src[i] != {
  141. return src[:i+]
  142. }
  143. }
  144. return nil
  145. }
  146.  
  147. func (this *AesTool) PKCS5Padding(ciphertext []byte, blockSize int) []byte {
  148. padding := blockSize - len(ciphertext)%blockSize
  149. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  150. return append(ciphertext, padtext...)
  151. }
  152.  
  153. func (this *AesTool) PKCS5UnPadding(origData []byte) []byte {
  154. length := len(origData)
  155. // 去掉最后一个字节 unpadding 次
  156. unpadding := int(origData[length-])
  157. origData = origData[:(length - unpadding)]
  158. fmt.Println("origData inner:", string(origData))
  159. return origData
  160. }
  161.  
  162. func mainecb(encryptData []byte) {
  163. //key := []byte{'#', '2', '&', '*', '#', ....}
  164. blickSize :=
  165. tool := NewAesTool(key, blickSize)
  166. decryptData, _ := tool.Decrypt(encryptData)
  167. fmt.Println(string(decryptData))
  168. }
  169. func NewAesTool(key []byte, blockSize int) *AesTool {
  170. return &AesTool{Key: key, BlockSize: blockSize}
  171. }
  172.  
  173. //====================================================
  174. //var global_int = 99
  175.  
  176. func main() {
  177. fmt.Println("Hello World!")
  178.  
  179. listener, err := net.Listen("tcp", "192.。。。")
  180. if err != nil {
  181. log.Fatal(err)
  182. }
  183. for {
  184. conn, err := listener.Accept()
  185. if err != nil {
  186. log.Println(err)
  187. continue
  188. }
  189. go handleConn(conn)
  190. }
  191.  
  192. fmt.Println("net finish...")
  193. }

go语言练习的更多相关文章

  1. C语言 · 高精度加法

    问题描述 输入两个整数a和b,输出这两个整数的和.a和b都不超过100位. 算法描述 由于a和b都比较大,所以不能直接使用语言中的标准数据类型来存储.对于这种问题,一般使用数组来处理. 定义一个数组A ...

  2. Windows server 2012 添加中文语言包(英文转为中文)(离线)

    Windows server 2012 添加中文语言包(英文转为中文)(离线) 相关资料: 公司环境:亚马孙aws虚拟机 英文版Windows2012 中文SQL Server2012安装包,需要安装 ...

  3. iOS开发系列--Swift语言

    概述 Swift是苹果2014年推出的全新的编程语言,它继承了C语言.ObjC的特性,且克服了C语言的兼容性问题.Swift发展过程中不仅保留了ObjC很多语法特性,它也借鉴了多种现代化语言的特点,在 ...

  4. C语言 · Anagrams问题

    问题描述 Anagrams指的是具有如下特性的两个单词:在这两个单词当中,每一个英文字母(不区分大小写)所出现的次数都是相同的.例如,"Unclear"和"Nuclear ...

  5. C语言 · 字符转对比

    问题描述 给定两个仅由大写字母或小写字母组成的字符串(长度介于1到10之间),它们之间的关系是以下4中情况之一: 1:两个字符串长度不等.比如 Beijing 和 Hebei 2:两个字符串不仅长度相 ...

  6. JAVA语言中的修饰符

    JAVA语言中的修饰符 -----------------------------------------------01--------------------------------------- ...

  7. Atitit 项目语言的选择 java c#.net  php??

    Atitit 项目语言的选择 java c#.net  php?? 1.1. 编程语言与技术,应该使用开放式的目前流行的语言趋势1 1.2. 从个人职业生涯考虑,java优先1 1.3. 从项目实际来 ...

  8. 【开源】简单4步搞定QQ登录,无需什么代码功底【无语言界限】

    说17号发超简单的教程就17号,qq核审通过后就封装了这个,现在放出来~~ 这个是我封装的一个开源项目:https://github.com/dunitian/LoTQQLogin ————————— ...

  9. InstallShield 脚本语言学习笔记

    InstallShield脚本语言是类似C语言,利用InstallShield的向导或模板都可以生成基本的脚本程序框架,可以在此基础上按自己的意愿进行修改和添加.     一.基本语法规则      ...

  10. 用C语言封装OC对象(耐心阅读,非常重要)

    用C语言封装OC对象(耐心阅读,非常重要) 本文的主要内容来自这里 前言 做iOS开发的朋友,对OC肯定非常了解,那么大家有没有想过OC中NSInteger,NSObject,NSString这些对象 ...

随机推荐

  1. Android Studio SVN配置

    一 . 原文链接:忽略文件[转]    https://blog.csdn.net/buaaroid/article/details/51546521 1.用Android Studio创建一个项目, ...

  2. AssetBundle Manager

    [AssetBundle Manager] AssetBundleManager是一个款Unity公司制作的Unity库. 1.Simulation Mode The main advantage o ...

  3. Hadoop详细安装步骤

    hadoop安装:(分布式模式)参考地址:http://dblab.xmu.edu.cn/blog/install-hadoop/ http://dblab.xmu.edu.cn/blog/insta ...

  4. 手机通过Charles抓取https包

      因为fiddler不能在mac上使用,而Charles是跨平台的,可以在mac上使用,所以需要了解一下Charles的使用   安装破解版Charles   下载破解版包,先启动一次未破解版的Ch ...

  5. 如何用 Postman 处理 json请求格式

    下边是其他博友写的 http://blog.163.com/huan12_8/blog/static/130519090201611711213719/

  6. JS的6种常见继承模式

    数天前在知乎看到有人阿里面试被问到这个问题,我来总结一下. 1. 原型链继承: function SuperType() { this.property = true; } SuperType.pro ...

  7. jenkin、SVN、archery集成openLDAP

    jenkins: 1.下载.安装插件 LDAP .Matrix Authorization Strategy 2. 系统管理 —> 全局安全配置 点击 启用安全,并且选择 LDAP 认证,这里有 ...

  8. 第十一章 串 (c1)KMP算法:从记忆力到预知力

  9. 179. Largest Number(INT, String)

    Given a list of non negative integers, arrange them such that they form the largest number. For exam ...

  10. ThreaLocal

    ThreadLocal概念:线程局部变量,是一种多线程间并发访问变量的解决方案.与其synchronized等加锁的方式不同,ThreadLocal完全不提供锁,而使用以空间换时间的手段,为每个线程提 ...