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;
                 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(""), 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
JniEnvironment+InstanceMethods.CallIntMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue
JniPeerMembers+JniInstanceMethods.InvokeVirtualInt32Method (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters)
HttpURLConnection.get_ResponseCode ()
AndroidClientHandler+<>c_DisplayClass46_0.<DoProcessRequest>b_2 ()
Task`1[TResult].InnerInvoke ()
Task.Execute ()
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)
AndroidClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
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 ) Socket closed Method)$$$*


· 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("", 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