1

I have 2 applications: Xamarin.Android client app that send value from SeekBar over Wifi and WinForms server that receive this value in real time. Everything works good but every time after ~40sec of data transferring android app throws System.Net.Sockets.SocketException with message "Too many open files".

My server code thats receive data:

    public void StartReceiving()
    {
        IPAddress localAdd = IPAddress.Parse(SERVER_IP);
        TcpListener listener = new TcpListener(localAdd, PORT_NO);
        listener.Start();

        while (true)
        {
            Socket client = listener.AcceptSocket();
            client.NoDelay = true;
            var childSocketThread = new Thread( () =>
            {
                byte[] datareceived = new byte[1];
                int size = client.Receive(datareceived);
                for (int i = 0; i < size; i++)
                {
                    Console.WriteLine(datareceived[0].ToString());
                }
                Console.WriteLine();
                //client.Close();
            });
            childSocketThread.Start();
        }
    }

Client code which sends value from SeekBar:

    private void Seek1_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e)
    {
        TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
        NetworkStream nwStream = client.GetStream();
        byte[] bytesToSend = new byte[1];
        bytesToSend[0] = Convert.ToByte(e.Progress);
        nwStream.Write(bytesToSend, 0, bytesToSend.Length);
    }

So my question is, what causes this problem and how can I solve it?

arnold20
  • 11
  • 1

1 Answers1

0

Your problem is the following: you open a socket for each call of the ProgressChanged event handler. There is a limited number of sockets that you can open on a machine and if you open them fast enough, you will end up in a System.Net.Sockets.SocketException.

A solution to this problem would be to make sure that you close the TCP connection gracefully. In that way you will release the sockets for further usage.

My opinion is that TCP is a bit overkill for this kind of communication. You can use HTTP to transfer the data. Your desktop app will be the server and the Xamarin app will be the client. In that way you will be freed by things like synchronization, connections states, etc.

Cosmin Ioniță
  • 3,598
  • 4
  • 23
  • 48