49 lines
1.3 KiB
Go

package client
import (
"fmt"
"log"
"net"
pb "net-tunnel/pkg/proto"
"strings"
"time"
)
func (c *Client) handleTCPData(msg *pb.Message_ProxyData) {
log.Printf("Received proxy data for connection: %v", msg.ProxyData.ConnId)
// 处理代理数据
hostPort := net.JoinHostPort(msg.ProxyData.ProxyConfig.LocalIp, fmt.Sprintf("%d", msg.ProxyData.ProxyConfig.LocalPort))
existingConn, ok := c.tcpConnections.Load(msg.ProxyData.ConnId)
var connState *TCPConnectionState
if ok {
connState = existingConn.(*TCPConnectionState)
} else {
conn, err := net.Dial(strings.ToLower(msg.ProxyData.ProxyConfig.Type.String()), hostPort)
if err != nil {
log.Printf("Failed to connect to proxy: %v", err)
return
}
switch strings.ToLower(msg.ProxyData.ProxyConfig.Type.String()) {
case "tcp":
if tcpConn, ok := conn.(*net.TCPConn); ok {
_ = tcpConn.SetKeepAlive(true)
_ = tcpConn.SetKeepAlivePeriod(30 * time.Second)
_ = tcpConn.SetNoDelay(true)
}
}
connState = NewTCPConnectionState(conn, msg.ProxyData.ConnId, msg.ProxyData.ProxyConfig, c.stream)
c.tcpConnections.Store(msg.ProxyData.ConnId, connState)
}
err := connState.WriteData(msg.ProxyData.Data)
if err != nil {
log.Printf("Failed to write data: %v", err)
connState.Close()
c.tcpConnections.Delete(msg.ProxyData.ConnId)
return
}
connState.StartReading()
}