Search code examples
c#queuesocketexception

SocketException An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full


from where this problem can be?

SocketException An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full

Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 50509);
EndPoint tmpRemote = (EndPoint)(sender);

newsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
newsock.Bind(ipep);

    while (thread_Listen == true && work == true)
        {
            try
            {
                Object state = new Object();
                **>> at this place >>** newsock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref tmpRemote, new AsyncCallback(DoReceiveFrom), state);
                Array.Clear(buffer, 0, buffer.Length);
            }
            catch (SocketException ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

This how func DoReceiveFrom looks like

private void DoReceiveFrom(IAsyncResult iar)
{
    try
    {
        Socket recvSock = (Socket)iar.AsyncState;
        EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
        int msgLen = recvSock.EndReceiveFrom(iar, ref clientEP);
        byte[] localMsg = GetAndCleanPacket(buffer);
        string[] packet = Encoding.ASCII.GetString(localMsg).Split(new Char[] { '|' });
        if (packet.Length > 0)
        {
            if (packet[0] == "ms")
            {
                // Connect
                if (packet[1] == "c") MSc(ip[0], packet[9], packet, clientEP);
                else if (packet[1] == "s") MSs(ip[0], packet);
                else if (packet[1] == "d") MDc(ip[0], packet);
            }
            else if (packet[0] == "p") ping(clientEP);
            else if (packet[0] == "sList") serverList(clientEP);
            else if (packet[0] == "bi") brGetInfo(packet, clientEP);
            else if (packet[0] == "error") AddError(packet[1], packet[2]);
        }
    }
    catch (InvalidOperationException)
    {
    }
    catch (SocketException)
    {
    }
    catch (Exception e)
    {
        errors.Add(e.ToString());
    }
}

Solution

  • Your while loop calls BeginReceiveFrom() at a very high rate. Until the operating system pulls the plug and refuses to allocate more resources, shouldn't take more than a fraction of a second.

    You'll have to do this differently, call BeginReceiveFrom only after you've received something. In DoReceiveFrom().