question

VuyiswaMaseko-8882 avatar image
0 Votes"
VuyiswaMaseko-8882 asked AgaveJoe commented

Java.Net.SocketException: Socket closed

Good Evening Everyone

im calling a web api function like this


  public async Task<List<USERS>> Get_All_Customers( )
         {
    
             List<USERS> results = null;
             try
             {
                 USERS m_model = new USERS
                 {
                     USER_ID = 1,
                     CURRENT_DATETIME = '2021/07/01'
                 };
                 var httpClient = new HttpClient();
    
                 httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                     
                     
                 var Json = JsonConvert.SerializeObject(m_model, new JsonSerializerSettings
                 {
                     ContractResolver = new DefaultContractResolver
                     {
                         IgnoreSerializableAttribute = false
                     }
                 });
    
    
                 HttpContent httpContent = new StringContent(Json, Encoding.UTF8, "application/json");
                 httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
    
                 var response = await Task.Run(() => httpClient.PostAsync(string.Format("https://www.myserver.com/api/MainCustomers_OnlineDates/Get_All_Customers"), httpContent));
    
                 if (response.StatusCode == System.Net.HttpStatusCode.OK)
                 {
                     var content = await response.Content.ReadAsStringAsync();
                     results = JsonConvert.DeserializeObject<List<USERS>>(content);
                 }
             }
             catch (Exception ex)
             {
                 await Task.Run(() => Crashes.TrackError(ex));
             }
    
             return results;
         }


This code work well most of the time , but some of my users get this exception which is logged in AppCentre and i only get this error on OS: Android 10

**Java.Net.SocketException: Socket closed
The Stacktrace
Java.Interop
JniEnvironment+InstanceMethods.CallIntMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue
args)
Java.Interop
JniPeerMembers+JniInstanceMethods.InvokeVirtualInt32Method (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters)
Java.Net
HttpURLConnection.get_ResponseCode ()
Xamarin.Android.Net
AndroidClientHandler+<>c_DisplayClass46_0.<DoProcessRequest>b_2 ()
System.Threading.Tasks
Task`1[TResult].InnerInvoke ()
System.Threading.Tasks
Task.Execute ()
Xamarin.Android.Net
AndroidClientHandler.DoProcessRequest (System.Net.Http.HttpRequestMessage request, Java.Net.URL javaUrl, Java.Net.HttpURLConnection httpConnection, System.Threading.CancellationToken cancellationToken, Xamarin.Android.Net.AndroidClientHandler+RequestRedirectionState redirectState)
Xamarin.Android.Net
AndroidClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
System.Net.Http
HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts)


Datalayerapi.Get_All_Online_Dates (System.Int32 userid, System.DateTime )
java.net.SocketException: Socket closed
com.android.org.conscrypt.NativeCrypto.SSL_read(Native Method)
com.android.org.conscrypt.NativeSsl.read NativeSsl.java:411
com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read ConscryptFileDescriptorSocket.java:583
com.android.okhttp.okio.Okio$2.read Okio.java:145
com.android.okhttp.okio.AsyncTimeout$2.read AsyncTimeout.java:213
com.android.okhttp.okio.RealBufferedSource.indexOf RealBufferedSource.java:317
com.android.okhttp.okio.RealBufferedSource.indexOf RealBufferedSource.java:311
com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict RealBufferedSource.java:207
com.android.okhttp.internal.http.Http1xStream.readResponse Http1xStream.java:395
com.android.okhttp.internal.http.Http1xStream.readResponseHeaders Http1xStream.java:146
com.android.okhttp.internal.http.HttpEngine.readNetworkResponse HttpEngine.java:900
com.android.okhttp.internal.http.HttpEngine.readResponse HttpEngine.java:772
com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute HttpURLConnectionImpl.java:493
com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse HttpURLConnectionImpl.java:429
com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode HttpURLConnectionImpl.java:560
com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode DelegatingHttpsURLConnection.java:106
com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode HttpsURLConnectionImpl.java:30*

Thanks



dotnet-xamarinformsdotnet-androiddotnet-aspnet-webapi
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The PostAsync() method is missing an await which can cause this issue. Remove the Task.Run() wrapper it does nothing except waste a thread. The async/await pattern looks like the following and is covered in the official docs.

 var response = await httpClient.PostAsync("https://www.myserver.com/api/MainCustomers_OnlineDates/Get_All_Customers", httpContent);

HttpClient is not designed properly according to the docs. You should have one static HttpClient for each service the application consumes.

Lastly, the Task.Run() in the catch block is mostly likely not designed correctly. Crashes.TrackError() probably should be an async method.


0 Votes 0 ·

0 Answers