Skip to content

Commit

Permalink
Added udp semaphore control
Browse files Browse the repository at this point in the history
  • Loading branch information
yosebyte authored Dec 2, 2024
1 parent 9026e6c commit 4e6409d
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
6 changes: 3 additions & 3 deletions internal/forward/tcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func HandleTCP(parsedURL *url.URL, whiteList *sync.Map) error {
return err
}
defer linkListen.Close()
tempSlot := make(chan struct{}, 1024)
semaphore := make(chan struct{}, 1024)
for {
linkConn, err := linkListen.AcceptTCP()
if err != nil {
Expand All @@ -37,9 +37,9 @@ func HandleTCP(parsedURL *url.URL, whiteList *sync.Map) error {
continue
}
linkConn.SetNoDelay(true)
tempSlot <- struct{}{}
semaphore <- struct{}{}
go func(linkConn net.Conn) {
defer func() { <-tempSlot }()
defer func() { <-semaphore }()
clientAddr := linkConn.RemoteAddr().String()
log.Info("Client connection established: [%v]", clientAddr)
if parsedURL.Fragment != "" {
Expand Down
7 changes: 5 additions & 2 deletions internal/forward/udp.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func HandleUDP(parsedURL *url.URL, whiteList *sync.Map) error {
return err
}
defer linkConn.Close()
semaphore := make(chan struct{}, 1024)
for {
buffer := make([]byte, 8192)
n, clientAddr, err := linkConn.ReadFromUDP(buffer)
Expand All @@ -41,7 +42,9 @@ func HandleUDP(parsedURL *url.URL, whiteList *sync.Map) error {
continue
}
}
go func() {
semaphore <- struct{}{}
go func(buffer []byte, n int, clientAddr *net.UDPAddr) {
defer func() { <-semaphore }()
targetConn, err := net.DialUDP("udp", nil, targetAddr)
if err != nil {
log.Error("Unable to dial target address: [%v] %v", targetAddr, err)
Expand Down Expand Up @@ -71,6 +74,6 @@ func HandleUDP(parsedURL *url.URL, whiteList *sync.Map) error {
return
}
log.Info("Transfer completed successfully")
}()
}(buffer, n, clientAddr)
}
}

0 comments on commit 4e6409d

Please sign in to comment.