Основное соединение было закрыто в 40-й итерации приложения VB.Net - PullRequest
0 голосов
/ 26 июня 2018

Этот вопрос появляется несколько раз на StackExchange, но я просто не могу его решить.В большинстве ответов говорится, что это происходит из-за проблем SSL или TLS и установки протокола на TLS10 или использования KeepAlive.

В моем случае я вызываю собственную конечную точку PHP и не использую SSL.Сервер размещен на GoDaddy.

Я получаю записи с сервера.Из-за большого размера возвращаемых данных я поместил вызовы в цикл.Цикл запускается и извлекает данные за 40-50 итераций, прежде чем выдать эту ошибку.Это не проблема тайм-аута, так как ошибка генерируется в течение миллисекунд.

Я подозреваю, что поток или соединение не закрываются, а в программе VB.Net заканчиваются ресурсы или на сервере слишком много открытых соединений.

Приведенный ниже код немного сокращен для удаления конфиденциальной информации:

        While True

        ' Create the request
        uri = New Uri(My.Settings.ServerURL & My.Settings.GetEmployeeRecords)
        request = DirectCast(WebRequest.Create(uri), HttpWebRequest)
        ' Add user credentials
        creds = New CredentialCache
        creds.Add(uri, "Basic", New NetworkCredential(My.Settings.UserId, My.Settings.Password))
        With request
            .Method = "POST"
            .ContentType = "application/x-www-form-urlencoded"
            .AutomaticDecompression = DecompressionMethods.GZip + DecompressionMethods.Deflate
            .Credentials = creds
            .KeepAlive = False
            .ProtocolVersion = HttpVersion.Version10
            .ConnectionGroupName = Guid.NewGuid().ToString()
            .UserAgent = "VB.NET App"
            .AllowAutoRedirect = False
        End With
        ' Add parameters
        strPostData = String.Format("offset={0}&limit={1}", iOffset, iLimit)
        request.ContentLength = strPostData.Length

        Try
            Using sw As New StreamWriter(request.GetRequestStream)
                sw.Write(strPostData)
                sw.Close()
            End Using
        Catch ex As Exception
            e.Result = "Error Setting Request Data"
            Exit Sub
        End Try

        ' Send the request to the server
        Try
            response = DirectCast(request.GetResponse, HttpWebResponse)
        Catch ex As WebException
            e.Result = "Error Sending Request" **<-- This is where it is thrown**
            Exit Sub
        End Try

        ' Open the response
        Try
            reader = New StreamReader(response.GetResponseStream)
        Catch ex As Exception
            e.Result = "Error Reading Request"
            Exit Sub
        End Try

        ' Read the full response
        rawresp = reader.ReadToEnd()
        reader.Close()
        response.Close()

        ' We should never get a blank response
        If rawresp = "" Or rawresp = "[]" Then
            e.Result = "Blank Response"
            Exit Sub
        End If

        ' The response should be in JSON. Parse it
        Try
            jResults = Linq.JObject.Parse(rawresp)
        Catch ex As Exception
            e.Result = "Error parsing response"
            Exit Sub
        End Try

        ' Get the complete response into jResults
        ' The jResults would contain {statuscode, statusDescription, data[]} where the data element would be an array of employees
        ' Check for error returned in response JSON
        If jResults("statusCode").ToString = "404" Then
            Exit While
        End If
        If jResults("statusCode").ToString <> "0" Then
            e.Result = "Error received from server"
            Exit Sub
        End If

        ' Get the array for the employee records
        Try
            jEmployees = Linq.JArray.Parse(jResults("data").ToString)
        Catch ex As Exception
            e.Result = "Response Does Not Contain Employee Array"
            Exit Sub
        End Try
        ' Everything is fine. Add the recordds to the local database
        SaveEmployeesToLocalDB(jEmployees)
        iCount = jEmployees.Count
        iOffset += iCount
        iTotalRecords += iCount
        If iCount = 0 Then
            Exit While
        End If
        If iTotalRecords Mod (20 * iLimit) = 0 Then
            Application.DoEvents()
            Threading.Thread.Sleep(3000)
        End If
    End While
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...