-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
50 lines (40 loc) · 1.14 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
package gognet
import (
"bytes"
"fmt"
"net"
"github.com/egor-erm/gognet/network"
)
type Conn struct {
Connection *net.UDPConn
Addr net.UDPAddr
closed chan bool
packets chan []byte
}
func (connection *Conn) Close(listener *Listener) {
delete(listener.connections, connection.Addr.String())
delete(listener.actions, connection.Addr.String())
connection.SendUnconnect()
connection.closed <- true
}
func (connection *Conn) CloseFromClient(listener *Listener) {
delete(listener.connections, connection.Addr.String())
delete(listener.actions, connection.Addr.String())
connection.closed <- true
}
func (connection *Conn) SendUnconnect() {
b := bytes.NewBuffer(make([]byte, 0))
(&network.Unconnected{}).Write(b)
_, _ = connection.Connection.WriteToUDP(b.Bytes(), &connection.Addr)
}
func (connection *Conn) Write(bytes []byte) (n int, err error) {
return connection.Connection.WriteToUDP(bytes, &connection.Addr)
}
func (connection *Conn) Read() (b []byte, err error) {
select {
case <-connection.closed:
return nil, fmt.Errorf("connection closed %x", connection.Addr)
case packet := <-connection.packets:
return packet, nil
}
}