HttpClient - Unable to write data to the transport connection: The socket has been shut down.

Hello,

I was given an application to debug lately and I encountered an error while sending a json. This request uses HttpClient, the content of the sending is 18Mb and contains 88 photos in base 64 in an HTML structure, in JSON. On the server, the php.ini is configured to accommodate requests of 100Mb max, so I do not think the error comes from the server.
The application makes a post data and throws an exception to the middle of the mailing.

Code:

        if (client.BaseAddress == null)
        {
            client.BaseAddress = new Uri(App.CommonDatas.API_URI);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Computer-id", CrossDeviceInfo.Current.Id);
        }

        if(!prevent_token && (need_token || app.token != null))
        {
            client.DefaultRequestHeaders.Remove("X-Token");
            client.DefaultRequestHeaders.Add("X-Token", app.token);
        }
        response = await client.PostAsync(path, new StringContent(jsonData))

StackTrace:

+       e   {System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.IO.IOException: Unable to write data to the transport connection: The socket has been shut down. ---> System.Net.Sockets.SocketException: The socket has been shut down
  at System.Net.Sockets.Socket.EndSend (System.IAsyncResult asyncResult) [0x00012] in <3e9b3e26c4694baab3f689687ad40612>:0 
  at System.Net.Sockets.NetworkStream.EndWrite (System.IAsyncResult asyncResult) [0x00057] in <3e9b3e26c4694baab3f689687ad40612>:0 
   --- End of inner exception stack trace ---
  at System.Net.Sockets.NetworkStream.EndWrite (System.IAsyncResult asyncResult) [0x0009b] in <3e9b3e26c4694baab3f689687ad40612>:0 
  at System.IO.Stream+<>c.<BeginEndWriteAsync>b__53_1 (System.IO.Stream stream, System.IAsyncResult asyncResult) [0x00000] in <fe08c003e91342eb83df1ca48302ddbb>:0 
  at System.Threading.Tasks.TaskFactory`1+FromAsyncTrimPromise`1[TResult,TInstance].Complete (TInstance thisRef, System.Func`3[T1,T2,TResult] endMethod, System.IAsyncResult asyncResult, System.Boolean requiresSynchronization) [0x00000] in <fe08c003e91342eb83df1ca48302ddbb>:0 
--- End of stack trace from previous location where exception was thrown ---
  at Mono.Net.Security.MobileAuthenticatedStream+<InnerWrite>d__67.MoveNext () [0x000d3] in <3e9b3e26c4694baab3f689687ad40612>:0 
--- End of stack trace from previous location where exception was thrown ---
  at Mono.Net.Security.AsyncProtocolRequest+<ProcessOperation>d__24.MoveNext () [0x00196] in <3e9b3e26c4694baab3f689687ad40612>:0 
--- End of stack trace from previous location where exception was thrown ---
  at Mono.Net.Security.AsyncProtocolRequest+<StartOperation>d__23.MoveNext () [0x0008b] in <3e9b3e26c4694baab3f689687ad40612>:0 
--- End of stack trace from previous location where exception was thrown ---
  at Mono.Net.Security.MobileAuthenticatedStream+<StartOperation>d__58.MoveNext () [0x001bf] in <3e9b3e26c4694baab3f689687ad40612>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Net.WebRequestStream+<ProcessWrite>d__33.MoveNext () [0x00270] in <3e9b3e26c4694baab3f689687ad40612>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Net.WebRequestStream+<WriteAsyncInner>d__32.MoveNext () [0x001aa] in <3e9b3e26c4694baab3f689687ad40612>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Net.Http.HttpClientHandler+<SendAsync>d__64.MoveNext () [0x0036e] in <25ebe1083eaf4329b5adfdd5bbb7aa57>:0 
   --- End of inner exception stack trace ---
  at System.Net.Http.HttpClientHandler+<SendAsync>d__64.MoveNext () [0x00489] in <25ebe1083eaf4329b5adfdd5bbb7aa57>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext () [0x000ca] in <25ebe1083eaf4329b5adfdd5bbb7aa57>:0 
--- End of stack trace from previous location where exception was thrown ---
  at Oracio.WebServices+<PostPutAsync>d__6`1[T].MoveNext () [0x007cb] in C:\oracio\android-old\Oracio\Classes\WebServices.cs:209 }  System.Net.Http.HttpRequestException

I can not provide you with json, it is private but I can validate that besides its size it is valid.
If you need information, for versions of packages for example, I am at your disposal.
I thank you in advance.

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    Which line throws this error? It seems you have used Sockets to upload your data, and it lost connection at some time.

  • MaxenceSAUNIERMaxenceSAUNIER USMember ✭✭✭

    This is the function:

    public static async Task<Tuple<bool, string>> PostPutAsync<T>(string path_url, T post_contents, string request_type, string filePath = "", int edl_id = -1, Utilisateur user = null)
    {
        try
        {
            if (path_url == "token/generer-token" || path_url == "logs/send-log")
                InitClient(false);
            else
                InitClient();
    
            string path = path_url;
    
            string json = "";
            if (!(post_contents is string))
                json = JsonConvert.SerializeObject(post_contents);
            else
                json = "" + post_contents;
    
            HttpResponseMessage response = new HttpResponseMessage();
            if (filePath != "")
            {
                Dictionary<string, string> datas = new Dictionary<string, string>();
    
                IFile file = await PCLStorage.FileSystem.Current.GetFileFromPathAsync(filePath);
                string htmlEDL = await file.ReadAllTextAsync(); 
    
                if (!string.IsNullOrWhiteSpace(htmlEDL))
                {
                    if (edl_id > -1)
                    {
                        List<EDLVFC> privloc = EDLVFC.getByEDLId(edl_id);
                        List<string> paraphes = new List<string>();
    
                        if (privloc.Count > 0)
                        {
                            if (user != null)
                            {
                                if (!string.IsNullOrWhiteSpace(user.paraphe))
                                {
                                    datas.Add("html", htmlEDL);
    
                                    string paraphesString = "";
                                    foreach (EDLVFC locat in privloc)
                                    {
                                        List<DelvhGtfvs> locatParaphes = DelvhGtfvs.getByEDLId(edl_id, 0, locat.id);
    
                                        if (locatParaphes.Count > 0)
                                        {
                                            DelvhGtfvs hjsklkik = locatParaphes[0];
    
                                            if (hjsklkik != null)
                                            {
                                                paraphesString += hjsklkik.paraphe + ";";
                                            }
                                        }
                                    }
                                    datas.Add("paraphesprivloc", paraphesString);
    
                                    datas.Add("parapheExpert", user.paraphe);
    
                                    List<Photo> photos = Photo.getByIdEDL(edl_id);
                                    string photosString = "";
                                    foreach (Photo photo in photos)
                                    {
                                        IFile iphoto = await FileSystem.Current.LocalStorage.GetFileAsync(photo.photoPath);
    
                                        Stream photoStream = await iphoto.OpenAsync(FileAccess.ReadAndWrite);
    
                                        byte[] filebytearray = new byte[photoStream.Length];
                                        photoStream.Read(filebytearray, 0, (int)photoStream.Length);
    
                                        photo.base64 = Convert.ToBase64String(filebytearray);
    
                                        string title = "";
                                        if (photo.typeLabel.Trim() == "")
                                            title = photo.elementLabel;
                                        else if (photo.elementLabel.Trim() == "")
                                            title = photo.typeLabel;
                                        else
                                            title = photo.typeLabel + "_" + photo.elementLabel;
                                        title = title.Replace(" : ", "_");
                                        title = title.Replace(" ", "-");
    
                                        photosString += title + ":" + photo.base64 + ";";
                                    }
                                    datas.Add("photos", photosString);
    
                                    string jsonData = JsonConvert.SerializeObject(datas);
                                    if (!string.IsNullOrWhiteSpace(jsonData)) 
                                    {
                                        try
                                        {
                                            using (response = await client.PostAsync(path, new StringContent(jsonData)))
                                            {
                                                //Not going to this part of the code;
                                            }
    
                                        }
                                        catch (Exception e)
                                        {
                                            //come her
                                            throw new Exception("test");
                                        }
                                    }
                                }
                                else
                                {
                                    Log.SaveLog("#private");
                                    await App._mainPage.DisplayAlert("Erreur", "#private", "Ok");
                                }
                            }
                            else
                            {
                                Log.SaveLog("#private");
                                await App._mainPage.DisplayAlert("Erreur", "#private", "Ok");
                            }
                        }
                        else
                        {
                            Log.SaveLog("#private");
                            await App._mainPage.DisplayAlert("Erreur", "#private", "Ok");
                        }
                    }
                }
                else
                {
                    Log.SaveLog("#private");
                    await App._mainPage.DisplayAlert("Erreur", "#private", "Ok");
                }
            }
            else
            {
                switch (request_type)
                {
                    case "post":
                        response = await client.PostAsync(path, new StringContent(json));
                        break;
                    case "put":
                        response = await client.PutAsync(path, new StringContent(json));
                        break;
                    default:
                        break;
                }
            }
    
            return new Tuple<bool, string>(response.IsSuccessStatusCode, await response.Content.ReadAsStringAsync());
        }
        catch (HttpRequestException e)
        {
            Log.SaveLog(e.Message);
            return new Tuple<bool, string>(false, e.Message);
        }
    }
    

    Thanks

  • bswanbswan USMember ✭✭

    I'm having similar issues. My web view is closing and I have an httplistener trying to respond but the socket it closed. It crashes my app. Was there ever a solution?

Sign In or Register to comment.