zoukankan      html  css  js  c++  java
  • C#UDP编程总结

    // 如果只使用一个EndPoint,维持一个引用。
    private static UdpClient udpClient;
    
    static void Main(string[] args)
    {
        if (udpClient != null)
        {
            // 这段很重要
            udpClient.Close();
        }
        udpClient = new UdpClient(10250);
        udpClient.Client.SendBufferSize = 120400;
        udpClient.Client.SendTimeout = 1000;
        udpClient.Client.ReceiveBufferSize = 120400;
        udpClient.Client.ReceiveTimeout = 1000;
        IPEndPoint endPoint;
        try
        {
            endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1025);
            udpClient.Connect(endPoint);
        }
        catch (Exception)
        {
            return;
            // 连不上目标端口
        }
        var bytes = new byte[0];
        udpClient.Send(bytes, bytes.Length);
        var receiver = new BackgroundWorker();
        receiver.WorkerSupportsCancellation = true;
        receiver.DoWork += delegate
            {
                while (receiver.CancellationPending)
                {
                    try
                    {
                        var a = udpClient.Receive(ref endPoint);
                        receiver.CancelAsync();
                    }
                    catch (Exception)
                    {
                        return;
                        // 对方断开连接或超时
                    }
                }
            };
        receiver.RunWorkerAsync();
    }
  • 相关阅读:
    HDU-1225 Football Score
    HDU-3854 LOOPS
    HDU-3863 No Gambling
    poj-2096 Collecting Bugs
    HDU-4336 Card Collector
    HDU-4405 Aeroplane chess
    2010上交:最小面积子矩阵
    VijosP1443:银河英雄传说
    VijosP1250:分组背包
    Vijos1221:神秘的配方
  • 原文地址:https://www.cnblogs.com/yao2yao4/p/3148997.html
Copyright © 2011-2022 走看看