Skip to content

Commit

Permalink
关闭超时tcp连接
Browse files Browse the repository at this point in the history
  • Loading branch information
csznet committed Mar 9, 2024
1 parent e4f104a commit 98f04bb
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 4 deletions.
47 changes: 44 additions & 3 deletions forward/forward.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ var bufPool = sync.Pool{
// 开启转发,负责分发具体转发
func Run(stats *ConnectionStats, wg *sync.WaitGroup) {
defer wg.Done()

defer releaseResources(stats) // 在函数返回时释放资源
var ctx, cancel = context.WithCancel(context.Background())
var innerWg sync.WaitGroup

Expand Down Expand Up @@ -142,6 +142,10 @@ func (cs *ConnectionStats) handleTCPConnection(wg *sync.WaitGroup, clientConn ne
defer wg.Done()
defer clientConn.Close()

// 设置连接读写超时时间
clientConn.SetReadDeadline(time.Now().Add(time.Duration(5) * time.Second))
clientConn.SetWriteDeadline(time.Now().Add(time.Duration(5) * time.Second))

remoteConn, err := net.Dial("tcp", cs.RemoteAddr+":"+cs.RemotePort)
if err != nil {
fmt.Println("连接远程地址时发生错误:", err)
Expand All @@ -150,7 +154,6 @@ func (cs *ConnectionStats) handleTCPConnection(wg *sync.WaitGroup, clientConn ne
defer remoteConn.Close()

cs.TCPConnections = append(cs.TCPConnections, clientConn, remoteConn) // 添加连接到列表

var copyWG sync.WaitGroup
copyWG.Add(2)

Expand Down Expand Up @@ -254,7 +257,7 @@ func (cs *ConnectionStats) copyBytes(dst, src net.Conn) {
// 定时打印和处理流量变化
func (cs *ConnectionStats) printStats(wg *sync.WaitGroup, ctx context.Context) {
defer wg.Done()
ticker := time.NewTicker(10 * time.Second)
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop() // 在函数结束时停止定时器
for {
select {
Expand All @@ -277,6 +280,16 @@ func (cs *ConnectionStats) printStats(wg *sync.WaitGroup, ctx context.Context) {
}
cs.TotalBytesOld = cs.TotalBytes
sql.UpdateForwardBytes(cs.Id, cs.TotalBytes)
fmt.Printf("【%s】端口 %s 当前连接数: %d\n", cs.Protocol, cs.LocalPort, len(cs.TCPConnections))
} else {
if cs.Protocol == "tcp" {
for i := len(cs.TCPConnections) - 1; i >= 0; i-- {
conn := cs.TCPConnections[i]
conn.Close()
// 从连接列表中移除关闭的连接
cs.TCPConnections = append(cs.TCPConnections[:i], cs.TCPConnections[i+1:]...)
}
}
}
cs.TotalBytesLock.Unlock()
//当协程退出时执行
Expand All @@ -285,3 +298,31 @@ func (cs *ConnectionStats) printStats(wg *sync.WaitGroup, ctx context.Context) {
}
}
}

// 关闭 TCP 连接并从切片中移除
func closeTCPConnections(stats *ConnectionStats) {
stats.TotalBytesLock.Lock()
defer stats.TotalBytesLock.Unlock()
for _, conn := range stats.TCPConnections {
conn.Close()
}
stats.TCPConnections = nil // 清空切片
}

// 清理缓冲区
func cleanupBuffer() {
// 如果有剩余的缓冲区,归还给池
for {
buf := bufPool.Get()
if buf == nil {
break
}
bufPool.Put(buf)
}
}

// 释放资源
func releaseResources(stats *ConnectionStats) {
closeTCPConnections(stats)
cleanupBuffer()
}
5 changes: 5 additions & 0 deletions utils/utils.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package utils

import (
"fmt"
"sync"

"csz.net/goForward/conf"
Expand All @@ -10,6 +11,10 @@ import (

// 增加转发并开启
func AddForward(newF conf.ConnectionStats) bool {
fmt.Print(newF)
if newF.LocalPort == conf.WebPort {
return false
}
id := sql.AddForward(newF)
if id > 0 {
stats := &forward.ConnectionStats{
Expand Down
2 changes: 1 addition & 1 deletion web/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func Run() {
})
} else {
c.HTML(200, "msg.tmpl", gin.H{
"msg": "添加失败,本地端口正在转发",
"msg": "添加失败,端口已占用",
"suc": false,
})
}
Expand Down

0 comments on commit 98f04bb

Please sign in to comment.