From 5e17d6fe0114f56b27ae645b4d333445668961f4 Mon Sep 17 00:00:00 2001 From: wwqgtxx Date: Tue, 16 Sep 2025 09:29:07 +0800 Subject: [PATCH] chore: simplify N.Relay --- common/net/sing.go | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/common/net/sing.go b/common/net/sing.go index 3545b6a4..72bfd972 100644 --- a/common/net/sing.go +++ b/common/net/sing.go @@ -1,9 +1,8 @@ package net import ( - "context" + "io" "net" - "runtime" "github.com/metacubex/mihomo/common/net/deadline" @@ -56,9 +55,37 @@ type CountFunc = network.CountFunc var Pipe = deadline.Pipe -// Relay copies between left and right bidirectionally. -func Relay(leftConn, rightConn net.Conn) { - defer runtime.KeepAlive(leftConn) - defer runtime.KeepAlive(rightConn) - _ = bufio.CopyConn(context.TODO(), leftConn, rightConn) +func closeWrite(writer io.Closer) error { + if c, ok := common.Cast[network.WriteCloser](writer); ok { + return c.CloseWrite() + } + 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 }