-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
73 lines (60 loc) · 1.17 KB
/
connection.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
package main
import (
"bufio"
"net"
)
type Connection struct {
ln net.Listener
conn net.Conn
reader *bufio.Reader
writer *bufio.Writer
}
func (c *Connection) Listen(address string) (string, error) {
var err error
err = c.StopListen()
c.ln, err = net.Listen("tcp", address)
if err != nil || c.ln == nil {
return "", err
}
if c.conn, err = c.ln.Accept(); err != nil {
return "", err
}
c.reader = bufio.NewReader(c.conn)
c.writer = bufio.NewWriter(c.conn)
return c.conn.RemoteAddr().String(), nil
}
func (c *Connection) StopListen() error {
if c.ln != nil {
err := c.ln.Close()
if err != nil {
return err
}
}
return nil
}
func (c *Connection) Connect(address string) (string, error) {
var err error
if c.conn, err = net.Dial("tcp", address); err != nil {
return "", err
}
c.reader = bufio.NewReader(c.conn)
c.writer = bufio.NewWriter(c.conn)
return c.conn.RemoteAddr().String(), nil
}
func (c *Connection) Disconnect() error {
if c.conn != nil {
err := c.conn.Close()
if err != nil {
return err
}
}
return nil
}
func NewConnection() *Connection {
return &Connection{
ln: nil,
conn: nil,
reader: nil,
writer: nil,
}
}