This repository has been archived by the owner on Sep 29, 2020. It is now read-only.
generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
81 lines (68 loc) · 1.31 KB
/
main.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
package main
import (
"net"
"os"
"os/signal"
"sync"
"time"
"github.com/spf13/pflag"
)
func main() {
var timeoutVar string
pflag.StringVarP(&timeoutVar, "timeout", "t", "10s", "timeout for create connection")
pflag.Parse()
args := pflag.Args()
if len(args) != 2 {
println("Wrong arguments count")
os.Exit(111)
}
timeout, err := time.ParseDuration(timeoutVar)
if err != nil {
println("unable to parse timeout")
os.Exit(1)
}
client := NewTelnetClient(net.JoinHostPort(args[0], args[1]), timeout, os.Stdin, os.Stdout)
if err := run(client); err != nil {
println("bad host")
os.Exit(1)
}
}
func run(client TelnetClient) error {
err := client.Connect()
if err != nil {
return err
}
println("connected ...")
wg := &sync.WaitGroup{}
wg.Add(2)
terminate := make(chan os.Signal, 1)
signal.Notify(terminate, os.Interrupt)
sendCh := make(chan struct{}, 1)
go func() {
err := client.Send()
if err != nil {
println("error while sending")
}
sendCh <- struct{}{}
}()
go func() {
defer wg.Done()
defer client.Close()
select {
case <-terminate:
println("interraupted...")
case <-sendCh:
println("exiting...")
}
}()
go func() {
defer wg.Done()
err := client.Receive()
if err != nil {
println("error while receiving")
return
}
}()
wg.Wait()
return nil
}