proxyport/app/proxy.go

73 lines
1.1 KiB
Go
Raw Normal View History

2023-01-18 14:33:17 +08:00
package app
import (
"fmt"
"git.makemake.in/test/mycommon/mylog"
"io"
"net"
)
func Run() {
for _, item := range ProxyMap {
go listenTcp(item)
}
select {}
}
func listenTcp(item ProxyItem) {
localAddr := fmt.Sprintf(":%d", item.LocalPort)
listen, err := net.Listen("tcp", localAddr)
if err != nil {
mylog.Errorf("listen err: %s", localAddr, err)
return
}
mylog.Infof("listen %s", localAddr)
for {
conn, err := listen.Accept()
if err != nil {
mylog.Errorf("conn accept err: %s", localAddr, err)
return
}
go proxyTcp(conn, item)
}
}
func proxyTcp(conn net.Conn, item ProxyItem) {
//defer conn.Close()
for _, addr := range item.RemoteAddr {
remoteConn, err := net.Dial("tcp", addr)
if err != nil {
mylog.Errorf("connect remote err: %s\n", err)
2023-01-18 14:33:39 +08:00
return
2023-01-18 14:33:17 +08:00
}
mylog.Infof("connect remote %s", addr)
go copyConn(conn, remoteConn)
go copyConn(remoteConn, conn)
}
}
func copyConn(src, dst net.Conn) {
defer func() {
src.Close()
dst.Close()
mylog.Warn("close conn")
}()
_, err := io.Copy(src, dst)
if err != nil {
mylog.Error(err)
return
}
//fmt.Println(written)
}