generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 0
/
telnet.go
78 lines (63 loc) · 1.21 KB
/
telnet.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
package main
import (
"errors"
"fmt"
"io"
"net"
"time"
)
const ConnType = "tcp"
var (
ErrInvalidIn = errors.New("in is invalid")
ErrInvalidOut = errors.New("out is invalid")
)
type TelnetClient interface {
Connect() error
io.Closer
Send() error
Receive() error
}
func NewTelnetClient(address string, timeout time.Duration, in io.ReadCloser, out io.Writer) TelnetClient {
return &Client{
address: address,
timeout: timeout,
in: in,
out: out,
}
}
type Client struct {
address string
timeout time.Duration
in io.ReadCloser
out io.Writer
conn net.Conn
}
func (c *Client) Connect() error {
var err error
if c.in == nil {
return ErrInvalidIn
}
if c.out == nil {
return ErrInvalidOut
}
c.conn, err = net.DialTimeout(ConnType, c.address, c.timeout)
if err != nil {
return err
}
return nil
}
func (c *Client) Close() error {
return c.conn.Close()
}
func (c *Client) Send() error {
if _, err := io.Copy(c.conn, c.in); err != nil {
return fmt.Errorf("failed to send message: %w", err)
}
return nil
}
func (c *Client) Receive() error {
if _, err := io.Copy(c.out, c.conn); err != nil {
return fmt.Errorf("failed to receive message: %w", err)
}
return nil
}