异步Udp消息的缓冲区

时间:2016-06-07 21:18:39

标签: c# udp

我正在使用以下代码来接收消息(我正在使用这种方式,因为我在等待消息时正在做某事)但是,我正在测试此连接并且我发送消息非常接近但看起来似乎就像其中一个人迷路一样。我不知道如何解决这个问题。如何启用“读取缓冲区”'选项或类似的东西?

谢谢..这里是代码:

//接收UDP消息的功能

 public static void ReceiveCallback(IAsyncResult ar)
    {

        UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;

        //IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

        Byte[] receiveBytes = u.EndReceive(ar, ref IpEndPoint_groupEP);
        received_data_from_client = Encoding.ASCII.GetString(receiveBytes);
        messageReceived = true;
        Logger("Received a message from : " + IpEndPoint_groupEP.ToString());
        u.Close();
    }

    public static void ReceiveMessages()
    {

        IpEndPoint_groupEP.Address = (IPAddress.Any);
        IpEndPoint_groupEP.Port = listenPort;

        //IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort);

        UdpClient u = new UdpClient(IpEndPoint_groupEP);

        UdpState s = new UdpState();

        s.e = IpEndPoint_groupEP;
        s.u = u;

        u.BeginReceive(new AsyncCallback(ReceiveCallback), s);

  while (!messageReceived)
            {
                    Thread.Sleep(50);
Console.writeLine("Hello")


}

我有u.close因为这个函数被调用多了一个。我有一个while循环,所以程序读取消息并对消息执行某些操作然后在完成后循环返回并调用ReceiveMessages函数以开始读取另一个消息。而且基本上当程序没有收到消息时,它会喊出“你好”

它的工作就像一个魅力。然而我意识到当两个或多个消息同时到达时,它只是读取其中一个而我正在丢失其他消息

1 个答案:

答案 0 :(得分:1)

问题是您正在关闭消息之间的端口。而不是这样做移动创建from django.conf import settings user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] database_url = 'postgresql://{user}:{password}@localhost:5432/{database_name}'.format( user=user, password=password, database_name=database_name, ) engine = create_engine(database_url, echo=False) df.to_sql(HistoricalPrices, con=engine)

之外的端口
ReceiveMessages()

但是因为你做public static void ReceiveCallback(IAsyncResult ar) { UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u; //IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e; Byte[] receiveBytes = u.EndReceive(ar, ref IpEndPoint_groupEP); received_data_from_client = Encoding.ASCII.GetString(receiveBytes); messageReceived = true; Logger("Received a message from : " + IpEndPoint_groupEP.ToString()); } public static UdpClient CreateClient() { IpEndPoint_groupEP.Address = (IPAddress.Any); IpEndPoint_groupEP.Port = listenPort; UdpClient u = new UdpClient(IpEndPoint_groupEP); return u; } public static void ReceiveMessages(UdpClient u) { UdpState s = new UdpState(); s.e = IpEndPoint_groupEP; s.u = u; u.BeginReceive(new AsyncCallback(ReceiveCallback), s); while (!messageReceived) { Thread.Sleep(50); Console.writeLine("Hello") } } 之后你做的唯一事情就是开始在循环中等待什么,你可能要考虑去除异步回调并直接调用BeginReceive并阻止这一点。