-
Notifications
You must be signed in to change notification settings - Fork 0
/
JSON_EchoClient.go
75 lines (62 loc) · 1.17 KB
/
JSON_EchoClient.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
71
72
73
74
75
/*
JSON_EchoClient
go run JSON_EchoClient.go localhost:1200
*/
package main
import (
"encoding/json"
"fmt"
"net"
"os"
)
type Person struct {
Name Name
Email []Email
}
type Name struct {
Family string
Personal string
}
type Email struct {
Kind string
Address string
}
// Person的toString方法
func (p Person) String() string {
s := p.Name.Personal + " " + p.Name.Family
for _, v := range p.Email {
s += "\n" + v.Kind + ": " + v.Address
}
return s
}
func main() {
person := Person{
Name: Name{Family: "Chu", Personal: "Tian Le"},
Email: []Email{
Email{Kind: "Work", Address: "[email protected]"},
Email{Kind: "Life", Address: "[email protected]"},
},
}
if len(os.Args) != 2 {
fmt.Println("Usage: ", os.Args[0], " host:port")
os.Exit(1)
}
service := os.Args[1]
conn, err := net.Dial("tcp", service)
checkError(err)
encoder := json.NewEncoder(conn)
decoder := json.NewDecoder(conn)
for n := 0; n < 10; n++ {
encoder.Encode(person)
var newPerson Person
decoder.Decode(&newPerson)
fmt.Println(newPerson.String())
}
os.Exit(0)
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
os.Exit(1)
}
}