Go gob TCP客户端和服务端通信示例代码

服务端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main

import (
"encoding/gob"
"fmt"
"net"
)

type P struct {
   M, N int
}

func handleConnection(conn net.Conn) {
   //decoder只需要new一次
   dec := gob.NewDecoder(conn)
   for {
      fmt.Println("Read data")
      p := &P{}
      //读取数据Go官方包已经封装在里面了
      err := dec.Decode(p)
      if err != nil {
         fmt.Println(err.Error())
         break
      }
      fmt.Println("Received : %+v", p)
   }
}

func main() {
   fmt.Println("Start server")
   ln, err := net.Listen("tcp", ":8080")
   if err != nil {
      // handle error
   }
   for {
      conn, err := ln.Accept()
      if err != nil {
         continue
      }
      go handleConnection(conn)
   }
}

客户端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import (
"encoding/gob"
"fmt"
"log"
"net"
"time"
)

type P struct {
   M, N int
}

func main() {
   fmt.Println("start client")
   conn, err := net.Dial("tcp", "localhost:8080")
   if err != nil {
      log.Fatal("Connection error", err)
   }

   //encoder同样只需要new一次
   encoder := gob.NewEncoder(conn)
   for i := 0; i < 3; i++ {
      p := &P{i, i + 1}
      encoder.Encode(p)
      fmt.Println("Send : %+v", p)

      time.Sleep(time.Second * 1)
   }
   conn.Close()
   fmt.Println("done")
}

服务端输出结果:
Start server
Read data
Received : %+v &{0 1}
Read data
Received : %+v &{1 2}
Read data
Received : %+v &{2 3}
Read data
EOF

客户端的输出结果:
start client
Send : %+v &{0 1}
Send : %+v &{1 2}
Send : %+v &{2 3}
done

发表评论

电子邮件地址不会被公开。 必填项已用*标注