我就廢話(huà)不多說(shuō)了,直接上代碼吧:
創(chuàng)新互聯(lián)2013年至今,先為天峨等服務(wù)建站,天峨等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢(xún)服務(wù)。為天峨企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。
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 指定服務(wù)監(jiān)聽(tīng)的端口") 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和端口,多個(gè)用','隔開(kāi)") flag.Parse() trueList = strings.Split(list, ",") if len(trueList) <= 0 { fmt.Println("后端IP和端口不能空,或者無(wú)效") 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("建立連接錯(cuò)誤:%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發(fā)送數(shù)據(jù)失敗:%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接收數(shù)據(jù)失敗:%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 實(shí)現(xiàn)tcp轉(zhuǎn)發(fā)代理的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持創(chuàng)新互聯(lián)。