zproxy/proxy/client.go

60 lines
1.4 KiB
Go
Raw Normal View History

2024-02-13 19:45:15 +08:00
package proxy
import (
"net"
"zproxy/zlog"
)
type UClientProxy struct {
2024-02-15 15:03:33 +08:00
serverAddr string
clientAddr string
2024-02-13 19:45:15 +08:00
}
2024-02-15 23:48:07 +08:00
func (client *UClientProxy) NewClientConnection(id uint32) *PacketConnect {
2024-02-15 15:03:33 +08:00
conn, err := net.Dial("tcp", client.clientAddr)
2024-02-13 19:45:15 +08:00
if err != nil {
2024-02-15 15:03:33 +08:00
zlog.Infof("connect local client error: %s %s", err.Error(), client.clientAddr)
return nil
2024-02-13 19:45:15 +08:00
}
2024-02-15 23:48:07 +08:00
return NewPacketConnect(conn, "local", id)
2024-02-15 15:03:33 +08:00
}
func (client *UClientProxy) NewTcpConnection(id uint32) *PacketConnect {
conn, err := net.Dial("tcp", client.serverAddr)
2024-02-13 19:45:15 +08:00
if err != nil {
2024-02-15 23:48:07 +08:00
zlog.Fatalf("connect server error: %d", id)
return nil
2024-02-13 19:45:15 +08:00
}
2024-02-15 23:48:07 +08:00
remote := NewPacketConnect(conn, "remote", id)
2024-02-15 15:03:33 +08:00
remote.WriteHeader(id)
if id == RemoteID {
return remote
}
2024-02-15 23:48:07 +08:00
local := client.NewClientConnection(id)
2024-02-15 15:03:33 +08:00
if local == nil {
err = remote.Close()
return nil
}
2024-02-15 23:48:07 +08:00
zlog.Infof("Forward %s => %s", remote.LocalAddr(), remote.Name())
go func() {
local.Forward(remote, 0)
//remote.SetReadDeadline(time.Now())
}()
2024-02-15 15:03:33 +08:00
go remote.Forward(local, 0)
return nil
}
func (client *UClientProxy) ServeTCP(serverAddr string, clientAddr string) error {
client.serverAddr = serverAddr
client.clientAddr = clientAddr
RemoteConn := client.NewTcpConnection(RemoteID)
zlog.Infof("connect to server %s", RemoteConn.Name())
2024-02-13 19:45:15 +08:00
for {
2024-02-15 15:03:33 +08:00
data := RemoteConn.ReadHeader()
if string(data[:4]) != "anki" {
2024-02-13 19:45:15 +08:00
zlog.Error("rcv package error:", data)
continue
}
2024-02-15 23:48:07 +08:00
id := packetEndian.Uint32(data[4:8])
2024-02-15 15:03:33 +08:00
go client.NewTcpConnection(id)
2024-02-13 19:45:15 +08:00
}
}