1

I am using Console application as a server on windows 10 Pro. Android application made with Unity Engine as Client. For both application I use TCP socket on the .Net framework.

Note: the server is always running on wire connection.

Everything work pretty well on both wire and Wi-Fi connections with no problem no meter how packet length is.

The Problem

Each evening the cellular network became too bad and the client app receive only part of the data when the data is little bigger about 50 kb

The code on the server side:

_socket.Send(Encoding.ASCII.GetBytes(s));

_socket: is an instance System.Net.Sockets.Socket.

s: is string.

The code on the client side:

public static void ReceiveData()
{ 
    message = string.Empty;
    _socket.BeginReceive(globalBuffer, 0, globalBuffer.Length, SocketFlags.None, ReceiveCallBack, null);
}
public static void ReceiveCallBack(IAsyncResult ar)
{
    int internalBuffer = _socket.EndReceive(ar);
    byte[] subtractedBuffer = new byte[internalBuffer];
    Array.Copy(globalBuffer, subtractedBuffer, internalBuffer);
    string stmp = Encoding.ASCII.GetString(subtractedBuffer);
    message += stmp;

    while (message.Contains("</Cargo>"))
    {
       string stringOne = message.Substring(0, message.IndexOf("</Cargo>") + "</Cargo>".Length);
       string stringLeft = message.Substring(message.IndexOf("</Cargo>") + "</Cargo>".Length);
       message = stringLeft;

       Thread thread = new Thread(TreatOrder);
       thread.Start(stringOne);
    }

    if (!(_socket.Poll(1000, SelectMode.SelectRead) && _socket.Available == 0))
    {
        NetWorkScript.LastConnectedTime = DateTime.Now;
        _socket.BeginReceive(globalBuffer, 0, globalBuffer.Length, SocketFlags.None, ReceiveCallBack, null);
    }
    else
    {
      Debug.log("Connection lost");
    }   
}

What I have notice:

The next line of code never executed

else
{
   Debug.log("Connection lost");
}  

The server keep receiving messages from the client on the same Socket instance by another thread and that is how came to know the connection is not broken unless TCP connection could be broken on one way only.

What I understand so far

The TCP will make sure the packets will arrive at the exact order.

The next line of code in my server application end its responsibility and the Operation System will carry on the mission to send the data.

_socket.Send(Encoding.ASCII.GetBytes(s));

What I am confused about

How the Operation System will deliver the data to the client?, why it is not keep trying until send all the data if the connection still exist?

Should I created my own protocol and send small packet then retransmit if client does not confirm receiving the packet?

hassane
  • 821
  • 6
  • 8

0 Answers0