当前位置:编程学习 > C#/ASP.NET >>

高手进 UDPSocket控件


请看下面的代码

错误在化线的部分

using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Diagnostics;
using System.Net.Sockets;
using System.Net;
using System.Windows.Forms;
using System.Threading;

namespace QQclass
{
     public partial  class UDPSocket:Component
    {
         private IPEndPoint ServerEndPoint = null;
         private UdpClient UDP_Server = new UdpClient();
         private System.Threading.Thread thdUdp;

         public delegate void DataArrivalEventHandler(byte[] Data, IPAddress Ip, int Port);
         public event DataArrivalEventHandler DataArrival;
         private string localHost = "127.0.0.1";
         [Browsable(true), Category("Local"), Description("本地IP地址")]

         public string LocalHost
         {
             get {return localHost; }
             set { localHost = value;}
         }

         private int localPort = 11000;
         [Browsable(true), Category("Local"), Description("本地端口号")]

         public int LocalPort
         {
             get { return localPort; }
             set { localPort = value; }
         }

         private bool active = false;
         [Browsable(true), Category("Local"), Description("激活监听")]

         public bool Active
         {
             get { return active; }
             set {

                 active = value;
                 if (active)
                 { OpenSocket(); }

                 else
                 {
                   CloseSocket()  ;
                 }

 

                }
         }



         public UDPSocket()
         {
            // InitializeComponent();         }

         public UDPSocket(IContainer container)
         {
             container.Add(this);
            // InitializeComponent();
         }

         private void OpenSocket()
         {
             Listener();

         }


         private void CloseSocket()
         {
             if (UDP_Server != null)
             
                 UDP_Server.Close();
             if (thdUdp != null)
             {
                 Thread.Sleep(30);
                 thdUdp.Abort();
             }
             
         }


         protected void Listener()
         {
             ServerEndPoint = new IPEndPoint(IPAddress.Any ,localPort);
             if (UDP_Server != null)
                 UDP_Server.Close();
             UDP_Server = new UdpClient(localPort);

             try
             {
                 thdUdp = new Thread(new ThreadStart(GetUDPDate));
                 thdUdp.Start();

             }

             catch (Exception e)
             {
                 MessageBox.Show(e.ToString());
             }

            

         }




         private void GetUDPDate()
         {
             while (active)
             {

                 try
                 {

                     byte[] Data = UDP_Server.Receive(ref ServerEndPoint);
                     if (DataArrival != null)
                     {
                         DataArrival(Data, ServerEndPoint.Address, ServerEndPoint.Port);
                     }

                     Thread.Sleep(0);
                 }

                 catch { }

             
             
         }

         }


         public void Send(System.Net.IPAddress Host, int Port, byte[] Data)
         {

             try
             {
                 IPEndPoint server = new IPEndPoint(Host, Port);
                 UDP_Server.Send(Data, Data.Length, server);



             }
             catch (Exception e)
             {
                 MessageBox.Show(e.ToString());
             }
         }
     




    }
}

--------------------编程问答-------------------- 上下这个长,翻起来很累啊。 --------------------编程问答-------------------- 关注下
帮顶 --------------------编程问答-------------------- 哪里划线了,是不是你注释的地方,
可能是如果要在线程中更新界面控件要是使用



            if (InvokeRequired)
            { 
                //传递一个委托
            }
--------------------编程问答-------------------- 是注释的地方(初始化组件)
你能直接说怎么解决吗?
引用 3 楼 myrroom 的回复:
哪里划线了,是不是你注释的地方,
可能是如果要在线程中更新界面控件要是使用


C# code


            if (InvokeRequired)
            { 
                //传递一个委托
            }
--------------------编程问答-------------------- 错误不要用MessageBox显示,可以用一个事件传递出来,

 public class SocketUDP : Component
    {
        private string m_Description;
        private IPEndPoint m_Server;
        private Container components;
        private Thread thdUdp;
        private UdpClient UDP_Server;
        private int UDP_Server_Port;

        /// <summary>
        /// 数据达到事件
        /// </summary>
        public event DataArrivalEventHandler DataArrival;
        private void OnDataArrival(byte[] data, IPAddress ip, int port)
        {
            if (this.DataArrival != null)
            {
                System.ComponentModel.ISynchronizeInvoke aSynch = this.DataArrival.Target as System.ComponentModel.ISynchronizeInvoke;
                if (aSynch != null && aSynch.InvokeRequired)
                    aSynch.Invoke(new DataArrivalEventHandler(OnDataArrival), new object[] { data, ip, port });
                else
                    this.DataArrival(data, ip, port);
            }
        }
        /// <summary>
        /// 套接字出错事件
        /// </summary>
        public event SocketErrorEventHandler SocketError;
        private void OnSocketError(string error)
        {
            if (this.SocketError != null)
            {
                System.ComponentModel.ISynchronizeInvoke aSynch = this.SocketError.Target as System.ComponentModel.ISynchronizeInvoke;
                if (aSynch != null && aSynch.InvokeRequired)
                    aSynch.Invoke(new SocketErrorEventHandler(SocketError), new object[] { error });
                else
                    this.SocketError(error);
            }
        }
        public SocketUDP()
        {
            this.components = null;
            this.m_Server = new IPEndPoint(IPAddress.Any, 0);
            this.UDP_Server = new UdpClient();
            this.m_Description = "";
            this.InitializeComponent();
        }

        public SocketUDP(IContainer container)
        {
            this.components = null;
            this.m_Server = new IPEndPoint(IPAddress.Any, 0);
            this.UDP_Server = new UdpClient();
            this.m_Description = "";
            container.Add(this);
            this.InitializeComponent();
        }
        /// <summary>
        /// 关闭套接字
        /// </summary>
        public void CloseSocket()
        {
            Thread.Sleep(30);
            try
            {
                if (this.UDP_Server != null)
                    this.UDP_Server.Close();
                if (this.thdUdp != null)
                    this.thdUdp.Abort();
            }
            catch (Exception e)
            {
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }
        /// <summary>
        /// 接受UDP数据
        /// </summary>
        private void GetUDPData()
        {
            while (true)
            {
                try
                {
                    byte[] rData = this.UDP_Server.Receive(ref this.m_Server);
                    this.OnDataArrival(rData, this.m_Server.Address, this.m_Server.Port);
                    Thread.Sleep(0);
                }
                catch (System.ObjectDisposedException)
                {
                    break;
                }
                catch (System.Threading.ThreadAbortException)
                {
                    break;
                }
                catch (Exception e)
                {
                    this.OnSocketError(e.ToString());
                }
            }
        }

        private void InitializeComponent()
        {
            this.components = new Container();
        }
        /// <summary>
        /// 开始侦听指定的端口
        /// </summary>
        /// <param name="Port"></param>
        public void Listen(int Port)
        {
            try
            {
                this.UDP_Server_Port = Port;
                this.UDP_Server = new UdpClient(Port);
                this.thdUdp = new Thread(new ThreadStart(this.GetUDPData));
                this.thdUdp.Start();
            }
            catch (Exception e)
            {
                this.OnSocketError(e.ToString());
            }
        }
        /// <summary>
        /// 发送数据到指定的IP与端口
        /// </summary>
        /// <param name="Host"></param>
        /// <param name="Port"></param>
        /// <param name="Data"></param>
        public void Send(IPAddress Host, int Port, byte[] Data)
        {
            try
            {
                IPEndPoint server = new IPEndPoint(Host, Port);
                this.UDP_Server.Send(Data, Data.Length, server);
            }
            catch (Exception e)
            {
                this.OnSocketError(e.ToString());
            }
        }

        [Category("UDPSocket"), Description("功能描述"), Browsable(true)]
        public string Description
        {
            get { return this.m_Description; }
            set { this.m_Description = value; }
        }

        [Category("UDPSocket"), Description("获得对方IP地址与端口号等信息."), Browsable(true)]
        public IPEndPoint Server
        {
            get { return this.m_Server; }
            set { this.m_Server = value; }
        }
        public int SocketUDPPort
        {
            get { return this.UDP_Server_Port; }
        }
        public delegate void DataArrivalEventHandler(byte[] data, IPAddress ip, int port);

        public delegate void SocketErrorEventHandler(string error);
    }
--------------------编程问答-------------------- 字太大,眼累 --------------------编程问答-------------------- 我怎么找不到UDPSOCKET,请问在什么地方啊
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,