-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
100 lines (83 loc) · 1.82 KB
/
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
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package laughing_fortnight
import (
"bufio"
"fmt"
"io"
"log"
"net"
"os"
"os/signal"
"syscall"
"time"
)
type ChatClient interface {
Dial(network, address string) (err error)
Close()
handleInput()
echoServer(done chan struct{})
}
type chatClient struct {
conn net.Conn
}
func NewChatClient() ChatClient {
return new(chatClient)
}
func (client *chatClient) Dial(network, address string) (err error){
client.conn, err = net.Dial(network, address)
return err
}
func (client *chatClient) Close(){
client.conn.Close()
}
func (client *chatClient) handleInput(){
var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)
for scanner.Scan(){
io.WriteString(client.conn, scanner.Text())
}
}
func (client *chatClient) echoServer(done chan struct{}){
for {
buf := make([]byte, 12000)
n, err := client.conn.Read(buf)
if err != nil {
log.Println("Connection closed by the server.")
break
}
fmt.Println("[SERVER] " + string(buf[0:n]))
print("> ")
buf = nil
}
done <- struct{}{}
}
func StartClient(retry uint8){
var err error
var ch chan os.Signal = make(chan os.Signal)
var client ChatClient = NewChatClient()
var done chan struct{} = make(chan struct{})
if err = client.Dial("tcp", "127.0.0.1:8888"); err != nil {
log.Println(err)
retryConnection(retry)
return
} else {
retry = 3
}
defer client.Close()
go func() {
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
<-ch
log.Println("\n\nDisconnecting from the server\n")
os.Exit(0)
}()
go client.handleInput()
go client.echoServer(done)
<-done
// Try to reconnect to a new server
retryConnection(retry)
}
func retryConnection(retry uint8) {
if retry == 0 {
return
}
time.Sleep(time.Duration(int64(9/retry)) * time.Second)
StartClient(retry - 1)
}