请给个完整源码,谢谢!

解决方案 »

  1.   

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;namespace UDPReceiver
    {
    public delegate void OnReceiveEventHandler(string xmlPack); /// <summary>
    /// MultiCast 的摘要说明。
    /// </summary>
    public class MultiCast
    {
    private string addr;
    private int port;
    private UdpClient subscriber;
    private bool bShutDown = true;
    private Thread thReceive; /// <summary>
    /// 数据到达事件
    /// </summary>
    public event OnReceiveEventHandler OnReceive;

    /// <summary>
    /// 构造
    /// </summary>
    /// <param name="multiCastIP">组播IP</param>
    /// <param name="udpPort">端口</param>
    public MultiCast(string multiCastIP,int udpPort)
    {
    addr = multiCastIP;
    port = udpPort;
    OnReceive += new OnReceiveEventHandler(MultiCast_OnReceive);
    } /// <summary>
    /// 启动监听
    /// </summary>
    public void Startup()
    {  
    if (!bShutDown)
    return; subscriber = new UdpClient(port); 
    IPAddress ipMultiCast = IPAddress.Parse(addr);

    try
    {
    subscriber.JoinMulticastGroup(ipMultiCast);
    }
    catch(Exception ex)
    {
    System.Windows.Forms.MessageBox.Show("无法加入到多播组[" + addr + "]\n\n" + ex.ToString());
    return;
    } //抛出监听线程
    bShutDown = false;
    thReceive = new Thread(new ThreadStart(Receive));
                thReceive.Start();   
    } /// <summary>
    /// 关闭监听
    /// </summary>
    public void ShutDown()
    {
    bShutDown = true;
    thReceive.Join(500); try
    {
    thReceive.Abort();
    }
    catch
    {

    } subscriber.Close();
    subscriber = null;
    } private void MultiCast_OnReceive(string xmlPack)
    {
    //do nothing
    }
    private void Receive()
    {
    byte[] bytes = null;
    IPEndPoint ipFrom = null;
    string xml = ""; while(!bShutDown)
    {
    bytes = subscriber.Receive(ref ipFrom);

    if (bytes != null)
    {
    if (bytes.Length > 0)
    {
    xml = System.Text.ASCIIEncoding.ASCII.GetString(bytes);
    //激发事件
    OnReceive(xml);
    }
                    }               
    }
    }
    }
    }
      

  2.   

    cooldingding 
     weisunding(鼎鼎)不是倒分?