I have designed an SSL Server in VB.NET.
However, when I receive multiple TCP requests (10s per second) to my server, I get a memory leak. Means memory increases every time I receive a request.
Procedure to simulate error:
- Listen to HTTPS (443) port.
- Make multiple request from Browser.
- Close connection after processing request.
This leads to increased memory usage by the program at every request.
I tried running GC.collect() but nothing works.
Kindly find attached following code:
Private HTTPS_Listener As Socket = Nothing
Private Sub ListenS()
Try
HTTPS_Listener = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim ep As New Net.IPEndPoint(IPAddress.Any, 443)
HTTPS_Listener.Bind(ep)
HTTPS_Listener.Listen(1024)
HTTPS_Listener.BeginAccept(New AsyncCallback(AddressOf DoSecureCallBack), Nothing)
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
End Sub
Private Sub DoSecureCallBack(ByVal ar As IAsyncResult)
Dim sock As Socket = Nothing
Try
sock = HTTPS_Listener.EndAccept(ar)
Console.WriteLine(vbCrLf + vbCrLf + vbCrLf + "Conn received " + Threading.Interlocked.Increment(iCon).ToString)
Catch ex As Exception
Add_Log(0, "ERROR", "WebServer", "Could not accept web connection." + vbCrLf + ex.Message)
Exit Sub
Finally
HTTPS_Listener.BeginAccept(New AsyncCallback(AddressOf DoSecureCallBack), Nothing)
End Try
Dim myNS As NetworkStream = Nothing
Dim mySSLStream As SslStream = Nothing
'Process Web Request
Dim bytesRead As Integer = -1
Try
myNS = New NetworkStream(sock, False)
mySSLStream = New SslStream(myNS, False)
mySSLStream.AuthenticateAsServer(cert_Socket, False, SslProtocols.Tls12, False)
mySSLStream.Write(btOut, 0, btOut.Length)
Catch ex As Exception
If bytesRead > 0 Then
Console.WriteLine("Could not process Web Request." + vbCrLf + ex.Message)
End If
Finally
If Not mySSLStream Is Nothing Then
mySSLStream.Close()
mySSLStream.Dispose()
End If
If Not myNS Is Nothing Then
myNS.Close()
myNS.Dispose()
End If
If Not sock Is Nothing Then
sock.Close()
End If
sock = Nothing
End Try
End Sub 'DoAcceptSocketCallback