UDP

        struct UdpState
        {
            public System.Net.IPEndPoint EP;
            public System.Net.Sockets.UdpClient UDPClient;
        }
public void ReceiveCallback(IAsyncResult ar)
        {
            UdpState MyUDP = (UdpState)ar.AsyncState;            string ReceiveString = Encoding.ASCII.GetString(MyUDP.UDPClient.EndReceive(ar, ref MyUDP.EP));
            ReceiveString = MyUDP.EP.Address.ToString() + "\n" + ReceiveString.Replace("\r\n", "\n");            MyUDP.UDPClient.BeginReceive(ReceiveCallback, MyUDP);
            listView1.Invoke(new AddTolstDiscoveredDevices(AddDiscoveryEntry), ReceiveString);
        }        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                GlobalUDP.UDPClient = new UdpClient();
                GlobalUDP.EP = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("255.255.255.255"), 30303);
                System.Net.IPEndPoint BindEP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 30303);
                byte[] DiscoverMsg = Encoding.ASCII.GetBytes("Discovery: Who is out there?");                GlobalUDP.UDPClient.Client.Bind(BindEP);                GlobalUDP.UDPClient.EnableBroadcast = true;
                GlobalUDP.UDPClient.MulticastLoopback = false;                GlobalUDP.UDPClient.BeginReceive(ReceiveCallback, GlobalUDP);                GlobalUDP.UDPClient.Send(DiscoverMsg, DiscoverMsg.Length, new System.Net.IPEndPoint(System.Net.IPAddress.Parse("255.255.255.255"), 30303));
            }
            catch
            {
                MessageBox.Show("Unable to transmit discovery message.  Check network connectivity and ensure that no other instances of this program are running.", "Error", MessageBoxButtons.OK);
                return;
            }
        }看了好久還是一知半解,
請看的懂的對代碼上標紅色的解釋下?如能對整個代碼運行過程解釋最好!謝謝

解决方案 »

  1.   

     MyUDP.UDPClient.BeginReceive(ReceiveCallback, MyUDP);
     GlobalUDP.UDPClient.BeginReceive(ReceiveCallback, GlobalUDP);                GlobalUDP.UDPClient.Send(DiscoverMsg, DiscoverMsg.Length, new System.Net.IPEndPoint(System.Net.IPAddress.Parse("255.255.255.255"), 30303));
    是紅色的
      

  2.   

    如果想深入学习或掌握,最好是找本网络变成的书看看,了解一下TCP和UDP协议,Socket编程。
    IP,子网掩码之类的一些必要知识。
      

  3.   

     BeginReceive 方法开始从客户端套接字异步读取数据
      

  4.   

    為什麼要執行2次 BeginReceive(ReceiveCallback, MyUDP)