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

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