UDP代理,如何维护/重用/清除连接客户端池?

时间:2016-03-21 10:09:37

标签: sockets go proxy udp

我在UDP-proxy中创建go,但在使用iperf进行一些负载测试时,我开始收到此错误:

socket: too many open files

在搜索和测试之后,我发现如果我使用map开放连接创建一个池,其中 *net.UDPAddr.String()包含UDP-proxy*net.UDPConn实例,如果客户端地址相同,我可以重用现有连接:

var clients   map[string]*UDPProxy.UDPProxy = make(map[string]*UDPProxy.UDPProxy) 

code块看起来像:

// wait for connections
for {
    n, clientAddr, err := conn.ReadFromUDP(buffer)
    if err != nil {
        log.Println(err)
    }
    counter++
    if *d {
        log.Printf("new connection from %s", clientAddr.String())
    }
    fmt.Printf("Connections: %d, clients: %d\n", counter, len(clients))
    proxy, found = clients[clientAddr.String()]
    if !found {
        // make new connection to remote server
        proxy = UDPProxy.New(conn, clientAddr, raddr_udp, *d)
        clients[clientAddr.String()] = proxy
    }
    go proxy.Start(buffer[0:n])
}

这似乎有效,但我现在遇到的问题是,我需要找到一种到期方式,在客户端存在时清理地图或者不再使用代理,这样我就可以避免多个未使用的连接

任何想法如何才能改善这一点甚至更好,我怎么能完全取代地图,我不知道channels是否可以提供帮助?

提前致谢。

1 个答案:

答案 0 :(得分:0)

由于您正在创建UDP代理,您可能知道必须提出自己的解决方案来决定何时“终止”代理会话。会话只是UDP的抽象 - 除非您使用的UDPProxy包已经建立了机制。

根据您创建UDP代理的原因,可能很容易随意清理连接...

因此,如果您知道客户端正在退出,请在代理上调用Close()方法(假设有一个)并在地图条目上使用delete。

如何确定客户退出取决于您。可以使用切片作为FIFO,或随机选择一个切片,或尝试为每个切片设置定时器。