Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by swparkaust · Aug 03, 2019 at 01:42 PM · networkingasyncasynchronoussocketstcp

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());
         }
     }
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by swparkaust · Aug 10, 2019 at 01:12 PM

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

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

153 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Unity Asynchronous Socket Client - Threading Problem 2 Answers

Can I use TcpListener.AllowNatTraversal or Socket.SetIPProtectionLevel in Unity ? 1 Answer

Game server crashes in release and debug build but not in editor (GetThreadContext failed) 0 Answers

tcp socket error message (C#) 1 Answer

Async execution with blocking methods 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges