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.
star/net/natserver.go

90 lines
1.8 KiB
Go

1 year ago
package net
import (
"bytes"
8 months ago
"context"
"encoding/hex"
1 year ago
"fmt"
"io"
"net"
"sync"
8 months ago
"sync/atomic"
1 year ago
"time"
)
8 months ago
// MSG_CMD_HELLO 控制链路主动链接参头 16byte
var MSG_CMD_HELLO, _ = hex.DecodeString("B6121127AF7ECDA1")
var MSG_CMD_HELLO_REPLY, _ = hex.DecodeString("B6121127AF7ECDA2")
1 year ago
8 months ago
// MSG_NEW_CONN_HELLO 交链路主动连接头 16byte
var MSG_NEW_CONN_HELLO, _ = hex.DecodeString("B6121127AF7ECDFF")
type NatServer struct {
sync.RWMutex
1 year ago
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
8 months ago
tcpConnPool chan net.Conn
stopCtx context.Context
stopFn context.CancelFunc
1 year ago
}
8 months ago
func (n *NatServer) Run() error {
if n.running != 0 {
return fmt.Errorf("Server Already Run")
1 year ago
}
8 months ago
n.stopCtx, n.stopFn = context.WithCancel(context.Background())
return nil
1 year ago
}
8 months ago
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 {
1 year ago
8 months ago
}
}
1 year ago
}
8 months ago
func (n *NatServer) runTcpListen() error {
atomic.AddInt32(&n.running, 1)
defer atomic.AddInt32(&n.running, -1)
listener, err := net.Listen("tcp", n.Addr)
1 year ago
if err != nil {
return err
}
8 months ago
n.listenTcp = listener
1 year ago
for {
8 months ago
conn, err := listener.Accept()
1 year ago
if err != nil {
continue
}
8 months ago
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)
//
1 year ago
}
}
8 months ago
io.ReadFull(conn, headedr)
1 year ago
}
}