Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Asynchronous socket hangs intermittently on iOS

Discussion in 'Connected Games' started by swparkaust, Aug 4, 2019.

  1. swparkaust

    swparkaust

    Joined:
    Dec 2, 2017
    Posts:
    2
    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:
    Code (CSharp):
    1.     using System.Collections;
    2.     using System.Collections.Generic;
    3.     using UnityEngine;
    4.     using System;
    5.     using System.Net;
    6.     using System.Net.Sockets;
    7.    
    8.     public class NetworkController : MonoBehaviour
    9.     {
    10.         public static NetworkController instance;
    11.    
    12.         private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    13.         private byte[] _receiveBuffer = new byte[8142];
    14.    
    15.         private List<byte> _inBuffer;
    16.    
    17.         void Awake()
    18.         {
    19.             if (!instance)
    20.             {
    21.                 instance = this;
    22.                 DontDestroyOnLoad(gameObject);
    23.             }
    24.             else
    25.             {
    26.                 Destroy(gameObject);
    27.             }
    28.         }
    29.    
    30.         // Start is called before the first frame update
    31.         void Start()
    32.         {
    33.             Connect();
    34.         }
    35.    
    36.         private void Connect()
    37.         {
    38.    
    39.             _inBuffer = new List<byte>();
    40.    
    41.             SetupServer();
    42.         }
    43.    
    44.         private void Disconnect()
    45.         {
    46.    
    47.             _clientSocket.Disconnect(true);
    48.             _inBuffer = null;
    49.         }
    50.    
    51.         IEnumerator Reconnect()
    52.         {
    53.             Disconnect();
    54.             yield return new WaitForSeconds(5);
    55.             Connect();
    56.         }
    57.    
    58.         private void SetupServer()
    59.         {
    60.             try
    61.             {
    62.                 _clientSocket.Connect(new IPEndPoint(IPAddress.Parse(IP), PORT));
    63.             }
    64.             catch (SocketException ex)
    65.             {
    66.                 Debug.Log(ex.Message);
    67.    
    68.                 StartCoroutine(Reconnect());
    69.             }
    70.    
    71.             _clientSocket.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
    72.    
    73.         }
    74.    
    75.         private void CheckForMessages()
    76.         {
    77.             while (true)
    78.             {
    79.                 if (_inBuffer.Count < sizeof(int))
    80.                 {
    81.                     return;
    82.                 }
    83.    
    84.                 int msgLength = BitConverter.ToInt32(_inBuffer.ToArray(), 0);
    85.                 msgLength = IPAddress.NetworkToHostOrder(msgLength);
    86.                 if (_inBuffer.Count < msgLength + 4)
    87.                 {
    88.                     return;
    89.                 }
    90.    
    91.                 byte[] message = _inBuffer.GetRange(4, msgLength).ToArray();
    92.                 ProcessMessage(message);
    93.    
    94.                 int amtRemaining = _inBuffer.Count - msgLength - sizeof(int);
    95.                 if (amtRemaining == 0)
    96.                 {
    97.                     _inBuffer = new List<byte>();
    98.                 }
    99.                 else
    100.                 {
    101.                     _inBuffer = _inBuffer.GetRange(msgLength + 4, amtRemaining);
    102.                 }
    103.    
    104.             }
    105.         }
    106.    
    107.         private void ReceiveCallback(IAsyncResult AR)
    108.         {
    109.             try
    110.             {
    111.                 int received = _clientSocket.EndReceive(AR);
    112.    
    113.                 if (received <= 0)
    114.                 {
    115.                     StartCoroutine(Reconnect());
    116.                     return;
    117.                 }
    118.    
    119.                 byte[] recData = new byte[received];
    120.                 Buffer.BlockCopy(_receiveBuffer, 0, recData, 0, received);
    121.    
    122.                 _inBuffer.AddRange(recData);
    123.                 CheckForMessages();
    124.    
    125.                 _clientSocket.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
    126.             }
    127.             catch (SocketException)
    128.             {
    129.                 StartCoroutine(Reconnect());
    130.             }
    131.         }
    132.    
    133.         private void SendData(byte[] data)
    134.         {
    135.             SocketAsyncEventArgs socketAsyncData = new SocketAsyncEventArgs();
    136.             socketAsyncData.SetBuffer(data, 0, data.Length);
    137.             try
    138.             {
    139.                 _clientSocket.SendAsync(socketAsyncData);
    140.             }
    141.             catch (Exception)
    142.             {
    143.                 StartCoroutine(Reconnect());
    144.             }
    145.         }
    146.     }
    147.  
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    5,954
    I'm wondering when this happens are you seeing the IOS client get stuck on a frame, or seeing Reconnect() being called repeatedly?
     
  3. swparkaust

    swparkaust

    Joined:
    Dec 2, 2017
    Posts:
    2
    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:

    Code (CSharp):
    1.     private ManualResetEvent sendDone =
    2.         new ManualResetEvent(false);
    3.  
    4.     private void SendData(byte[] data)
    5.     {
    6.         _clientSocket.BeginSend(data, 0, data.Length, 0,
    7.             new AsyncCallback(SendCallback), null);
    8.  
    9.         sendDone.WaitOne();
    10.         sendDone.Reset();
    11.     }
    12.  
    13.     private void SendCallback(IAsyncResult ar)
    14.     {
    15.         try
    16.         {
    17.             int bytesSent = _clientSocket.EndSend(ar);
    18.  
    19.             sendDone.Set();
    20.         }
    21.         catch (Exception)
    22.         {
    23.             StartCoroutine(Reconnect());
    24.         }
    25.     }