Forum Cross Platform with Xamarin

socket.SendFile not working in iOS

I've written a mobile app that takes a picture and sends it to a server via a TCP socket connection. It works great in the Android version but in iOS two blocks of data are sent and it hangs. The code is simply socket.SendFile(file.Path). Has anyone been able to solve this or can someone give me some ideas what to try?

Tagged:

Best Answer

  • ColeXColeX Member, Xamarin Team Xamurai
    Accepted Answer

    Try this workaround : Use BeginSend instead of SendAsync. Put a thread lock between BeginSend and in the callback where you call EndSend .

        private ManualResetEvent sendDone =
            new ManualResetEvent(false);
    
        private void SendData(byte[] data)
        {
            _clientSocket.BeginSend(data, 0, data.Length, 0,
                new AsyncCallback(SendCallback), null);
    
            sendDone.WaitOne();
            sendDone.Reset();
        }
    
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                int bytesSent = _clientSocket.EndSend(ar);
    
                sendDone.Set();
            }
            catch (Exception)
            {
                StartCoroutine(Reconnect());
            }
        }
    

    Refer to https://stackoverflow.com/a/57442428/8187800 .


    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

Answers

  • ColeXColeX Member, Xamarin Team Xamurai
    Accepted Answer

    Try this workaround : Use BeginSend instead of SendAsync. Put a thread lock between BeginSend and in the callback where you call EndSend .

        private ManualResetEvent sendDone =
            new ManualResetEvent(false);
    
        private void SendData(byte[] data)
        {
            _clientSocket.BeginSend(data, 0, data.Length, 0,
                new AsyncCallback(SendCallback), null);
    
            sendDone.WaitOne();
            sendDone.Reset();
        }
    
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                int bytesSent = _clientSocket.EndSend(ar);
    
                sendDone.Set();
            }
            catch (Exception)
            {
                StartCoroutine(Reconnect());
            }
        }
    

    Refer to https://stackoverflow.com/a/57442428/8187800 .


    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

  • This worked perfectly! Thank you ColeX.

Sign In or Register to comment.