forked from haveachin/infrared
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
130 lines (106 loc) · 2.26 KB
/
conn.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package infrared
import (
"bufio"
"crypto/cipher"
"io"
"net"
"time"
"github.com/haveachin/infrared/protocol"
)
type PacketWriter interface {
WritePacket(p protocol.Packet) error
}
type PacketReader interface {
ReadPacket() (protocol.Packet, error)
}
type PacketPeeker interface {
PeekPacket() (protocol.Packet, error)
}
type conn struct {
net.Conn
r *bufio.Reader
w io.Writer
}
type Listener struct {
net.Listener
}
func Listen(addr string) (Listener, error) {
l, err := net.Listen("tcp", addr)
return Listener{Listener: l}, err
}
func (l Listener) Accept() (Conn, error) {
conn, err := l.Listener.Accept()
if err != nil {
return nil, err
}
return wrapConn(conn), nil
}
// Conn is a minecraft Connection
type Conn interface {
net.Conn
PacketWriter
PacketReader
PacketPeeker
Reader() *bufio.Reader
}
// wrapConn warp an net.Conn to infared.conn
func wrapConn(c net.Conn) *conn {
return &conn{
Conn: c,
r: bufio.NewReader(c),
w: c,
}
}
// Dial create a Minecraft connection
func Dial(addr string) (Conn, error) {
conn, err := net.Dial("tcp", addr)
if err != nil {
return nil, err
}
return wrapConn(conn), nil
}
// DialTimeout acts like DialMC but takes a timeout.
func DialTimeout(addr string, timeout time.Duration) (Conn, error) {
conn, err := net.DialTimeout("tcp", addr, timeout)
if err != nil {
return nil, err
}
return wrapConn(conn), nil
}
func (c *conn) Read(b []byte) (int, error) {
return c.r.Read(b)
}
func (c *conn) Write(b []byte) (int, error) {
return c.w.Write(b)
}
// ReadPacket read a Packet from Conn.
func (c *conn) ReadPacket() (protocol.Packet, error) {
return protocol.ReadPacket(c.r)
}
// PeekPacket peeks a Packet from Conn.
func (c *conn) PeekPacket() (protocol.Packet, error) {
return protocol.PeekPacket(c.r)
}
//WritePacket write a Packet to Conn.
func (c *conn) WritePacket(p protocol.Packet) error {
pk, err := p.Marshal()
if err != nil {
return err
}
_, err = c.w.Write(pk)
return err
}
// SetCipher sets the decode/encode stream for this Conn
func (c *conn) SetCipher(ecoStream, decoStream cipher.Stream) {
c.r = bufio.NewReader(cipher.StreamReader{
S: decoStream,
R: c.Conn,
})
c.w = cipher.StreamWriter{
S: ecoStream,
W: c.Conn,
}
}
func (c *conn) Reader() *bufio.Reader {
return c.r
}