Modular 、Functional enhancement

This commit is contained in:
刘河
2019-04-08 17:01:08 +08:00
parent 0c87b4119a
commit 824b12a2f8
41 changed files with 754 additions and 242 deletions

View File

@@ -1,8 +1,10 @@
package proxy
import (
"encoding/binary"
"github.com/cnlh/nps/lib/common"
"github.com/cnlh/nps/lib/conn"
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
"net"
"strconv"
"time"
@@ -15,10 +17,12 @@ type P2PServer struct {
}
type p2p struct {
provider *conn.Conn
visitor *conn.Conn
visitorAddr string
providerAddr string
provider *conn.Conn
visitor *conn.Conn
visitorAddr string
providerAddr string
providerNatType int32
visitorNatType int32
}
func NewP2PServer(p2pPort int) *P2PServer {
@@ -35,49 +39,57 @@ func (s *P2PServer) Start() error {
}
func (s *P2PServer) p2pProcess(c *conn.Conn) {
//获取密钥
var (
f string
b []byte
err error
v *p2p
ok bool
f string
b []byte
err error
v *p2p
ok bool
natType int32
)
if b, err = c.GetShortContent(32); err != nil {
return
}
//获取角色
//get role
if f, err = c.ReadFlag(); err != nil {
return
}
//get nat type
if err := binary.Read(c, binary.LittleEndian, &natType); err != nil {
return
}
if v, ok = s.p2p[string(b)]; !ok {
v = new(p2p)
s.p2p[string(b)] = v
}
logs.Trace("new p2p connection ,role %s , password %s, nat type %s ,local address %s", f, string(b), strconv.Itoa(int(natType)), c.RemoteAddr().String())
//存储
if f == common.WORK_P2P_VISITOR {
logs.Warn("try visitor")
v.visitorAddr = c.Conn.RemoteAddr().String()
v.visitorNatType = natType
v.visitor = c
for {
time.Sleep(time.Second)
for i := 20; i > 0; i-- {
if v.provider != nil {
v.provider.WriteLenContent([]byte(v.visitorAddr))
binary.Write(v.provider, binary.LittleEndian, v.visitorNatType)
break
}
time.Sleep(time.Second)
}
if _, err := v.provider.ReadFlag(); err == nil {
v.visitor.WriteLenContent([]byte(v.providerAddr))
delete(s.p2p, string(b))
} else {
}
v.provider = nil
} else {
v.providerAddr = c.Conn.RemoteAddr().String()
v.providerNatType = natType
v.provider = c
for {
time.Sleep(time.Second)
for i := 20; i > 0; i-- {
if v.visitor != nil {
v.provider.WriteLenContent([]byte(v.visitorAddr))
v.visitor.WriteLenContent([]byte(v.providerAddr))
binary.Write(v.visitor, binary.LittleEndian, v.providerNatType)
break
}
time.Sleep(time.Second)
}
v.visitor = nil
}
}