Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C BeginReceiveFrom给了我一个错误_C#_Sockets - Fatal编程技术网

C# C BeginReceiveFrom给了我一个错误

C# C BeginReceiveFrom给了我一个错误,c#,sockets,C#,Sockets,我需要一个程序来听几个机器发送一些UDP的状态。我从一个聊天程序中剪切并粘贴了一些内容,使其正常工作,但在启动时,我遇到了一个错误,无法执行套接字上的操作,因为系统缺少足够的缓冲区空间,或者因为队列已满。如果我确定了错误,那么一切都正常。在下面的代码中,如果我删除Whiletrue,我不会得到错误,但我只得到一个条目。我想,但可能是错误的回调将继续运行,每次它得到的数据将发送给处理。我相信这就是我的问题所在,但我无法解决如何解决它,因此如何在不轮询套接字的情况下继续接收数据 private vo

我需要一个程序来听几个机器发送一些UDP的状态。我从一个聊天程序中剪切并粘贴了一些内容,使其正常工作,但在启动时,我遇到了一个错误,无法执行套接字上的操作,因为系统缺少足够的缓冲区空间,或者因为队列已满。如果我确定了错误,那么一切都正常。在下面的代码中,如果我删除Whiletrue,我不会得到错误,但我只得到一个条目。我想,但可能是错误的回调将继续运行,每次它得到的数据将发送给处理。我相信这就是我的问题所在,但我无法解决如何解决它,因此如何在不轮询套接字的情况下继续接收数据

private void Form1_Load(object sender, EventArgs e)
{
    try
   {
        CheckForIllegalCrossThreadCalls = false;

        //We are using UDP sockets
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        //Assign the any IP of the machine and listen on port number 701
        IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 701);

        //Bind this address to the server
        serverSocket.Bind(ipEndPoint);

        IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
        //The epSender identifies the incoming clients
        EndPoint epSender = (EndPoint)ipeSender;


        while (true)
        {

            //Start receiving data
            serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

不要将BeginReceiveFrom放入循环中。把它自己放回去。您需要做的是在OnReceive函数中放置另一个BeginReceive,这将获取下一组数据。

如果可能,请包括OnReceive的代码。删除可怕的CheckForIllegalCrossThreadCalls分配。删除根本错误的whiletrue循环。您现在编写正确代码的几率会大得多。