forked from xiaojiong/DhtCrawler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Network.go
52 lines (42 loc) · 813 Bytes
/
Network.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
package DhtCrawler
import (
"net"
)
type Network struct {
Dht *DhtNode
Conn *net.UDPConn
}
func NewNetwork(dhtNode *DhtNode) *Network {
nw := new(Network)
nw.Dht = dhtNode
nw.Init()
return nw
}
func (nw *Network) Init() {
addr := new(net.UDPAddr)
var err error
nw.Conn, err = net.ListenUDP("udp", addr)
if err != nil {
panic(err)
}
laddr := nw.Conn.LocalAddr().(*net.UDPAddr)
nw.Dht.node.Ip = laddr.IP
nw.Dht.node.Port = laddr.Port
}
func (nw *Network) Listening() {
buf := make([]byte, 1000)
for {
_, raddr, err := nw.Conn.ReadFromUDP(buf)
if err != nil {
continue
}
nw.Dht.krpc.Decode(string(buf), raddr)
}
}
func (nw *Network) Send(m []byte, addr *net.UDPAddr) error {
_, err := nw.Conn.WriteToUDP(m, addr)
if err != nil {
nw.Dht.log.Println(err)
}
return err
}