I'm new to Go and I'm trying to build a simple TCP server. I've attached my code below. Whenever a client disconnects, it will be added to server.deadConns.
If I use a simple Client and keep connecting and disconnecting to the TCP Server (code below), the memory usage of my Golang app just keeps going up. If I then stop connecting and reconnecting my Client and wait, the memory usage will slowly start to go down. It takes a long time for it to go down but it will.
I noticed this issue when I was running my TCP server on Azure and the memory usage on the VM just kept going up until the machine crashed. I checked the logs and saw that there was some clients that just kept connecting and disconnecting all the time. I then tried it locally on my own machine and noticed that the same thing happens.
//NewTCPServer Creates the TCP Server
func NewTCPServer(port string, logger *logrus.Logger) *TCPServer {
server := new(TCPServer)
server.socketAPI = socketapi.NewSocketAPI(logger)
newConns := make(chan net.Conn, 128)
server.deadConns = make(chan net.Conn, 128)
server.sessions = make(map[net.Conn]*types.ClientSession)
fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000") + ": Listening to: " + port)
listener, err := net.Listen("tcp", ":"+port)
if err != nil {
panic(err)
}
go func() {
for {
conn, err := listener.Accept()
if err != nil {
panic(err)
}
fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000") + ": Connected: " + conn.RemoteAddr().String())
newConns <- conn
}
}()
go func(server *TCPServer) {
for {
select {
case conn := <-newConns:
session := new(types.ClientSession)
tcp := createTCPSocket(&conn, server)
session.Socket = tcp
server.sessions[conn] = session
case deadConn := <-server.deadConns:
sess, ok := server.sessions[deadConn]
if ok {
fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000") + ": Found session")
if server.socketAPI.StopSubscriptionOnClose(sess) {
delete(server.sessions, deadConn)
}
}
fmt.Println(time.Now().Format("2006-01-02 15:04:05.000000") + ": Delete session!")
_ = deadConn.Close()
sess.Socket = nil
sess = nil
}
}
}(server)
return server
}