chore: simplify N.Relay

This commit is contained in:
wwqgtxx 2025-09-16 09:29:07 +08:00
parent 8cdfd87d1e
commit 5e17d6fe01

View File

@ -1,9 +1,8 @@
package net package net
import ( import (
"context" "io"
"net" "net"
"runtime"
"github.com/metacubex/mihomo/common/net/deadline" "github.com/metacubex/mihomo/common/net/deadline"
@ -56,9 +55,37 @@ type CountFunc = network.CountFunc
var Pipe = deadline.Pipe var Pipe = deadline.Pipe
// Relay copies between left and right bidirectionally. func closeWrite(writer io.Closer) error {
func Relay(leftConn, rightConn net.Conn) { if c, ok := common.Cast[network.WriteCloser](writer); ok {
defer runtime.KeepAlive(leftConn) return c.CloseWrite()
defer runtime.KeepAlive(rightConn) }
_ = bufio.CopyConn(context.TODO(), leftConn, rightConn) return writer.Close()
}
// Relay copies between left and right bidirectionally.
// like [bufio.CopyConn] but remove unneeded [context.Context] handle and the cost of [task.Group]
func Relay(leftConn, rightConn net.Conn) {
defer func() {
_ = leftConn.Close()
_ = rightConn.Close()
}()
ch := make(chan struct{})
go func() {
_, err := bufio.Copy(leftConn, rightConn)
if err == nil {
_ = closeWrite(leftConn)
} else {
_ = leftConn.Close()
}
close(ch)
}()
_, err := bufio.Copy(rightConn, leftConn)
if err == nil {
_ = closeWrite(rightConn)
} else {
_ = rightConn.Close()
}
<-ch
} }