コード例 #1
0
        async Task DiscoverUdp(IPAddress local, IPEndPoint ep)
        {
            XTrace.WriteLine("DiscoverUdp: {0} -> {1}", local, ep);

            // 构建请求
            var enc = new JsonEncoder();
            var msg = enc.CreateRequest("Api/Info", null);
            var req = msg.ToPacket().ReadBytes();

            var udp = new UdpClient(ep.AddressFamily)
            {
                EnableBroadcast = true
            };

            if (local != null)
            {
                udp.Client.Bind(new IPEndPoint(local, Rand.Next(1000, 60000)));
            }

            // 发送
            udp.Send(req, req.Length, ep);

            // 多次接收
            while (true)
            {
                try
                {
                    var source = new CancellationTokenSource(3_000);
                    var rs     = await udp.ReceiveAsync(source.Token);

                    if (rs.Buffer != null)
                    {
                        msg = new DefaultMessage();
                        msg.Read(rs.Buffer);

                        if (enc.Decode(msg, out var action, out var code, out var data) && code == 0)
                        {
                            // 解码结果
                            var result = enc.DecodeResult(action, data, msg);
                            XTrace.WriteLine("Receive[{0}] {1}", udp.Client.LocalEndPoint, result.ToJson());

                            var ai = enc.Convert(result, typeof(ApiItem)) as ApiItem;
                            if (ai != null)
                            {
                                Invoke(() => ShowItem(ai));
                            }
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    break;
                }
            }
        }