golang 实现tcp转发代理的方法
我就废话不多说了,直接上代码吧:
packagemain import( "flag" "fmt" "io" "net" "os" "strings" "sync" ) varlocksync.Mutex vartrueList[]string varipstring varliststring funcmain(){ 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,",") iflen(trueList)<=0{ fmt.Println("后端IP和端口不能空,或者无效") os.Exit(1) } server() } funcserver(){ lis,err:=net.Listen("tcp",ip) iferr!=nil{ fmt.Println(err) return } deferlis.Close() for{ conn,err:=lis.Accept() iferr!=nil{ fmt.Println("建立连接错误:%v\n",err) continue } fmt.Println(conn.RemoteAddr(),conn.LocalAddr()) gohandle(conn) } } funchandle(sconnnet.Conn){ defersconn.Close() ip,ok:=getIP() if!ok{ return } dconn,err:=net.Dial("tcp",ip) iferr!=nil{ fmt.Printf("连接%v失败:%v\n",ip,err) return } ExitChan:=make(chanbool,1) gofunc(sconnnet.Conn,dconnnet.Conn,Exitchanbool){ _,err:=io.Copy(dconn,sconn) fmt.Printf("往%v发送数据失败:%v\n",ip,err) ExitChan<-true }(sconn,dconn,ExitChan) gofunc(sconnnet.Conn,dconnnet.Conn,Exitchanbool){ _,err:=io.Copy(sconn,dconn) fmt.Printf("从%v接收数据失败:%v\n",ip,err) ExitChan<-true }(sconn,dconn,ExitChan) <-ExitChan dconn.Close() } funcgetIP()(string,bool){ lock.Lock() deferlock.Unlock() iflen(trueList)<1{ return"",false } ip:=trueList[0] trueList=append(trueList[1:],ip) returnip,true }
以上这篇golang实现tcp转发代理的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。