1
0
mirror of https://github.com/fumiama/WireGold.git synced 2026-06-10 03:28:22 +08:00
Files
WireGold/gold/link/link.go
2021-10-25 01:01:22 +08:00

68 lines
1.2 KiB
Go

package link
import (
"errors"
"net"
"sync"
"github.com/fumiama/WireGold/gold/head"
"github.com/sirupsen/logrus"
)
type Link struct {
PubicKey [32]byte
EndPoint string
KeepAlive int64
pipe chan *head.Packet
peerip net.IP
endpoint *net.UDPAddr
allowedips []*net.IPNet
hasKeepRuning bool
status int
}
const (
LINK_STATUS_DOWN = iota
LINK_STATUS_HALFUP
LINK_STATUS_UP
)
var (
connections = make(map[string]*Link)
connmapmu sync.RWMutex
myconn *net.UDPConn
)
func Connect(peer string) (*Link, error) {
p, ok := IsInPeer(net.ParseIP(peer).String())
if ok {
p.keepAlive()
return p, nil
}
return nil, errors.New("peer not exist")
}
func (l *Link) Close() {
connmapmu.Lock()
delete(connections, l.peerip.String())
connmapmu.Unlock()
l.status = LINK_STATUS_DOWN
}
func (l *Link) Read() *head.Packet {
return <-l.pipe
}
func (l *Link) Write(p *head.Packet) (n int, err error) {
p.Data, err = l.Encode(p.Data)
if err == nil {
var d []byte
d, err = p.Mashal(me.String(), l.peerip.String())
logrus.Debugln("[link] write data", string(d))
if err == nil {
n, err = myconn.WriteToUDP(d, l.endpoint)
}
}
return
}