-
Notifications
You must be signed in to change notification settings - Fork 0
/
peerInfo.go
71 lines (61 loc) · 1.78 KB
/
peerInfo.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
package DAG
import (
"context"
"encoding/json"
"github.com/EternallyAscend/GoToolkits/pkg/cryptography/hash"
"github.com/EternallyAscend/GoToolkits/pkg/network/tcp"
"github.com/EternallyAscend/GoToolkits/pkg/network/udp"
"log"
"net"
"strconv"
)
func GetDefaultPeerInfo() *PeerInfo {
return &PeerInfo{
Address: DefaultIP,
Port: DefaultPort,
TcpPort: DefaultTcpPort,
}
}
type PeerInfo struct {
Address string `json:"address" yaml:"address"`
Port uint `json:"port" yaml:"port"`
TcpPort uint `json:"tcpPort" yaml:"tcpPort"`
}
func (that *PeerInfo) HashString() string {
// TODO Add Random Id for Peers to Calculate Hash Value.
return hash.SHA512String([]byte(that.Address + strconv.Itoa(int(that.Port))))
//return hash.MD5String([]byte(that.Address + strconv.Itoa(int(that.Port))))
}
func UnpackPeerInfo(data []byte) *PeerInfo {
p := &PeerInfo{}
err := json.Unmarshal(data, p)
if nil != err {
log.Println("Unmarshal peerInfo failed,", err)
return nil
}
return p
}
func UnpackPeerInfoList(data []byte) map[string]*PeerInfo {
var pList map[string]*PeerInfo
err := json.Unmarshal(data, &pList)
if nil != err {
log.Println(string(data))
log.Println("Unmarshal peerInfo list failed,", err)
return nil
}
return pList
}
func (that *PeerInfo) UdpListen(f func([]byte), ctx context.Context) {
// TODO Using context for interrupting.
udp.ListenViaUdp4(f, that.Port)
}
func (that *PeerInfo) UdpSendToPeer(data []byte) error {
return udp.SendViaUdp4(that.Address, that.Port, data)
}
func (that *PeerInfo) TcpCommunicateWithPeer(method uint, data []byte) {
tcp.RequestViaTcp4(that.Address, that.TcpPort, SenderTcpFunc, method, data)
}
func (that *PeerInfo) TcpListen(f func(conn *net.Conn)) {
// TODO Using context for interrupting.
tcp.ListenViaTcp4(f, that.TcpPort)
}