Skip to content

Commit 118a230

Browse files
authored
refactor: enhance cancellation handling in commonTCPLoop and commonTCPOnce using context
1 parent 0dd7bee commit 118a230

File tree

1 file changed

+24
-8
lines changed

1 file changed

+24
-8
lines changed

internal/common.go

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -763,13 +763,21 @@ func (c *Common) commonTCPLoop() {
763763

764764
c.logger.Debug("Tunnel connection: %v <-> %v", remoteConn.LocalAddr(), remoteConn.RemoteAddr())
765765

766-
// 注册取消函数
767-
c.cancelMap.Store(id, func() {
766+
// 创建子上下文用于取消
767+
ctx, cancel := context.WithCancel(c.ctx)
768+
c.cancelMap.Store(id, cancel)
769+
defer func() {
770+
cancel()
771+
c.cancelMap.Delete(id)
772+
}()
773+
774+
// 通过连接关闭机制实现取消
775+
go func() {
776+
<-ctx.Done()
768777
if targetConn != nil {
769778
targetConn.Close()
770779
}
771-
})
772-
defer c.cancelMap.Delete(id)
780+
}()
773781

774782
// 构建并发送启动信号
775783
launchURL := &url.URL{
@@ -1129,13 +1137,21 @@ func (c *Common) commonTCPOnce(signalURL *url.URL) {
11291137
targetConn = &conn.StatConn{Conn: targetConn, RX: &c.tcpRX, TX: &c.tcpTX, Rate: c.rateLimiter}
11301138
c.logger.Debug("Target connection: %v <-> %v", targetConn.LocalAddr(), targetConn.RemoteAddr())
11311139

1132-
// 注册取消函数
1133-
c.cancelMap.Store(id, func() {
1140+
// 创建子上下文用于取消
1141+
ctx, cancel := context.WithCancel(c.ctx)
1142+
c.cancelMap.Store(id, cancel)
1143+
defer func() {
1144+
cancel()
1145+
c.cancelMap.Delete(id)
1146+
}()
1147+
1148+
// 通过连接关闭机制实现取消
1149+
go func() {
1150+
<-ctx.Done()
11341151
if targetConn != nil {
11351152
targetConn.Close()
11361153
}
1137-
})
1138-
defer c.cancelMap.Delete(id)
1154+
}()
11391155

11401156
// 发送PROXY v1
11411157
if err := c.sendProxyV1Header(signalURL.Host, targetConn); err != nil {

0 commit comments

Comments
 (0)