Asynchronous socket hangs intermittently on iOS

Hello,

I’m currently working on a Network Controller script, which uses C# Socket class to communicate with a dedicated server.

It makes use of asynchronous callback methods so that it sends/receives data asynchronously and processes them accordingly.

Most of the time, it works perfectly cross-platform (iOS and Android).

However, sometimes the socket would silently “hang” without any explicit error, neither sending nor receiving any more data from server. (In my testing it always happened on an iOS client.)

I double-checked just to be sure it’s not a problem on the server side.

Interestingly, the server sees the socket connection with the affected client still alive, and force-quitting the client still causes it to disconnect. It’s just calls to send/recv that fails.

Other, unaffected devices continue to send and receive data just fine.

The only way to recover from this is to forcefully close and reopen socket, which is impractical given that no Exception seems to be raised when this happens. (I once had “InvalidOperationException: No operation in progress” on a call to SendAsync which I am now handling – but why is this happening anyway?)

What could be the cause?

Here are some of the code:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using System;
    using System.Net;
    using System.Net.Sockets;
   
    public class NetworkController : MonoBehaviour
    {
        public static NetworkController instance;
   
        private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private byte[] _receiveBuffer = new byte[8142];
   
        private List<byte> _inBuffer;
   
        void Awake()
        {
            if (!instance)
            {
                instance = this;
                DontDestroyOnLoad(gameObject);
            }
            else
            {
                Destroy(gameObject);
            }
        }
   
        // Start is called before the first frame update
        void Start()
        {
            Connect();
        }
   
        private void Connect()
        {
   
            _inBuffer = new List<byte>();
   
            SetupServer();
        }
   
        private void Disconnect()
        {
   
            _clientSocket.Disconnect(true);
            _inBuffer = null;
        }
   
        IEnumerator Reconnect()
        {
            Disconnect();
            yield return new WaitForSeconds(5);
            Connect();
        }
   
        private void SetupServer()
        {
            try
            {
                _clientSocket.Connect(new IPEndPoint(IPAddress.Parse(IP), PORT));
            }
            catch (SocketException ex)
            {
                Debug.Log(ex.Message);
   
                StartCoroutine(Reconnect());
            }
   
            _clientSocket.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
   
        }
   
        private void CheckForMessages()
        {
            while (true)
            {
                if (_inBuffer.Count < sizeof(int))
                {
                    return;
                }
   
                int msgLength = BitConverter.ToInt32(_inBuffer.ToArray(), 0);
                msgLength = IPAddress.NetworkToHostOrder(msgLength);
                if (_inBuffer.Count < msgLength + 4)
                {
                    return;
                }
   
                byte[] message = _inBuffer.GetRange(4, msgLength).ToArray();
                ProcessMessage(message);
   
                int amtRemaining = _inBuffer.Count - msgLength - sizeof(int);
                if (amtRemaining == 0)
                {
                    _inBuffer = new List<byte>();
                }
                else
                {
                    _inBuffer = _inBuffer.GetRange(msgLength + 4, amtRemaining);
                }
   
            }
        }
   
        private void ReceiveCallback(IAsyncResult AR)
        {
            try
            {
                int received = _clientSocket.EndReceive(AR);
   
                if (received <= 0)
                {
                    StartCoroutine(Reconnect());
                    return;
                }
   
                byte[] recData = new byte[received];
                Buffer.BlockCopy(_receiveBuffer, 0, recData, 0, received);
   
                _inBuffer.AddRange(recData);
                CheckForMessages();
   
                _clientSocket.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
            }
            catch (SocketException)
            {
                StartCoroutine(Reconnect());
            }
        }
   
        private void SendData(byte[] data)
        {
            SocketAsyncEventArgs socketAsyncData = new SocketAsyncEventArgs();
            socketAsyncData.SetBuffer(data, 0, data.Length);
            try
            {
                _clientSocket.SendAsync(socketAsyncData);
            }
            catch (Exception)
            {
                StartCoroutine(Reconnect());
            }
        }
    }

I’m wondering when this happens are you seeing the IOS client get stuck on a frame, or seeing Reconnect() being called repeatedly?

Neither, the game continued without its state being updated nor catching any connection drop.

Anyways, after some trials, I now seem to have resolved the problem.

Here’s what I have done:

Use BeginSend instead of SendAsync. Put a thread lock between BeginSend and in the callback where you call EndSend, so that each BeginSend gets an EndSend before another BeginSend.

Here’s the code:

    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());
        }
    }