您好,登錄后才能下訂單哦!
我就廢話不多說了,直接上代碼吧:
package main import ( "flag" "fmt" "io" "net" "os" "strings" "sync" ) var lock sync.Mutex var trueList []string var ip string var list string func main() { flag.StringVar(&ip, "l", ":9897", "-l=0.0.0.0:9897 指定服務監聽的端口") flag.StringVar(&list, "d", "127.0.0.1:1789,127.0.0.1:1788", "-d=127.0.0.1:1789,127.0.0.1:1788 指定后端的IP和端口,多個用','隔開") flag.Parse() trueList = strings.Split(list, ",") if len(trueList) <= 0 { fmt.Println("后端IP和端口不能空,或者無效") os.Exit(1) } server() } func server() { lis, err := net.Listen("tcp", ip) if err != nil { fmt.Println(err) return } defer lis.Close() for { conn, err := lis.Accept() if err != nil { fmt.Println("建立連接錯誤:%v\n", err) continue } fmt.Println(conn.RemoteAddr(), conn.LocalAddr()) go handle(conn) } } func handle(sconn net.Conn) { defer sconn.Close() ip, ok := getIP() if !ok { return } dconn, err := net.Dial("tcp", ip) if err != nil { fmt.Printf("連接%v失敗:%v\n", ip, err) return } ExitChan := make(chan bool, 1) go func(sconn net.Conn, dconn net.Conn, Exit chan bool) { _, err := io.Copy(dconn, sconn) fmt.Printf("往%v發送數據失敗:%v\n", ip, err) ExitChan <- true }(sconn, dconn, ExitChan) go func(sconn net.Conn, dconn net.Conn, Exit chan bool) { _, err := io.Copy(sconn, dconn) fmt.Printf("從%v接收數據失敗:%v\n", ip, err) ExitChan <- true }(sconn, dconn, ExitChan) <-ExitChan dconn.Close() } func getIP() (string, bool) { lock.Lock() defer lock.Unlock() if len(trueList) < 1 { return "", false } ip := trueList[0] trueList = append(trueList[1:], ip) return ip, true }
以上這篇golang 實現tcp轉發代理的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。