You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
1.8 KiB
Go
90 lines
1.8 KiB
Go
package net
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
)
|
|
|
|
// MSG_CMD_HELLO 控制链路主动链接参头 16byte
|
|
var MSG_CMD_HELLO, _ = hex.DecodeString("B6121127AF7ECDA1")
|
|
var MSG_CMD_HELLO_REPLY, _ = hex.DecodeString("B6121127AF7ECDA2")
|
|
|
|
// MSG_NEW_CONN_HELLO 交链路主动连接头 16byte
|
|
var MSG_NEW_CONN_HELLO, _ = hex.DecodeString("B6121127AF7ECDFF")
|
|
|
|
type NatServer struct {
|
|
sync.RWMutex
|
|
cmdTCPConn net.Conn
|
|
listenTcp net.Listener
|
|
listenUDP *net.UDPConn
|
|
Addr string
|
|
Port int
|
|
lastTCPHeart int64
|
|
lastUDPHeart int64
|
|
Passwd string
|
|
DialTimeout int64
|
|
UDPTimeout int64
|
|
running int32
|
|
tcpConnPool chan net.Conn
|
|
stopCtx context.Context
|
|
stopFn context.CancelFunc
|
|
}
|
|
|
|
func (n *NatServer) Run() error {
|
|
if n.running != 0 {
|
|
return fmt.Errorf("Server Already Run")
|
|
}
|
|
n.stopCtx, n.stopFn = context.WithCancel(context.Background())
|
|
return nil
|
|
}
|
|
|
|
func (n *NatServer) cmdTcploop(conn net.Conn) error {
|
|
var header = make([]byte, 16)
|
|
for {
|
|
c, err := conn.Read(header)
|
|
if err != nil {
|
|
//todo
|
|
}
|
|
if c != 16 {
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
func (n *NatServer) runTcpListen() error {
|
|
atomic.AddInt32(&n.running, 1)
|
|
defer atomic.AddInt32(&n.running, -1)
|
|
listener, err := net.Listen("tcp", n.Addr)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
n.listenTcp = listener
|
|
for {
|
|
conn, err := listener.Accept()
|
|
if err != nil {
|
|
continue
|
|
}
|
|
headedr := make([]byte, 16)
|
|
conn.SetReadDeadline(time.Now().Add(time.Millisecond * 700))
|
|
c, err := conn.Read(headedr)
|
|
if err == nil && c == 16 {
|
|
if bytes.Equal(headedr, MSG_CMD_HELLO) {
|
|
if n.cmdTCPConn != nil {
|
|
n.cmdTCPConn.Close()
|
|
}
|
|
n.cmdTCPConn = conn
|
|
conn.Write(MSG_CMD_HELLO_REPLY)
|
|
//
|
|
}
|
|
}
|
|
io.ReadFull(conn, headedr)
|
|
}
|
|
}
|