一个简单的 TCP Socket 的示例,使用 gob 处理传输的数据。

server.go

 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main

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

type personInfo struct {
        Name  string
        Age   int32
        Phone string
        Addr  string
}

const (
        BUF_SIZE = 1024
)

func handleConnection(conn *net.TCPConn) {
        if conn == nil {
                return
        }
        defer conn.Close()

        data := make([]byte, BUF_SIZE)
        for {
                n, err := conn.Read(data)
                if err == io.EOF {
                        fmt.Println("Read connection data failed:", err)
                        break
                }
                fmt.Printf("Read %v byte data\n", n)

                b := bytes.NewBuffer(data)
                dec := gob.NewDecoder(b)

                info := personInfo{}
                dec.Decode(&info)
                fmt.Printf("Server receive data: %v\n", info)
        }
        return
}

func main() {
        tcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8087")
        if err != nil {
                fmt.Println("ResolveTCPAddr failed:", err)
                return
        }

        l, err := net.ListenTCP("tcp", tcpAddr)
        if err != nil {
                fmt.Println("Listen port error:", err)
                return
        }

        for {
                conn, err := l.AcceptTCP()
                fmt.Printf("The client: %s connected\n", conn.RemoteAddr().String())
                if err != nil {
                        fmt.Println("Accept error:", err)
                        continue
                }

                go handleConnection(conn)
        }
}

client.go

 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
package main

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

type personInfo struct {
        Name  string
        Age   int32
        Phone string
        Addr  string
}

func main() {
        tcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8087")
        if err != nil {
                fmt.Println("ResolveTCPAddr failed:", err)
                return
        }

        conn, err := net.DialTCP("tcp", nil, tcpAddr)
        if err != nil {
                fmt.Println("Create connection failed:", err)
                return
        }

        info := personInfo{"Maya", 18, "13277085678", "Hubei China"}
        var b bytes.Buffer
        enc := gob.NewEncoder(&b)
        enc.Encode(&info)
        for {
                conn.Write(b.Bytes())
                fmt.Println(b.Bytes())
                <-time.After(time.Second * 3)
        }
        conn.Close()
}