日期:2014-05-18  浏览次数:20785 次

C# Socket多线程程序占用CPU90%多
C# code

namespace date_sender
{
    public partial class Form1 : Form
    {
        private TcpListener tl;
        private NetworkStream ns;

        public delegate void MyDelegate(string temp);
        class ClientTcp
        {

            //设置网络流局部对象
            private NetworkStream ns;

            //声明类型为MyDelegate的事件MyEvent
            public event MyDelegate MyEvent;

            //构造函数中接收参数以初始化
            public ClientTcp(NetworkStream ns)
            {
                this.ns = ns;
            }

            //服务器端线程所调用的方法
            public void TcpRead()
            {
                //listBox1.Items.Add("TcpRead Begin...");
                Console.WriteLine("TcpRead Begin...");
                //获得相关的封装流
                while (true)
                {
                    try
                    {
                        byte[] bytes = new byte[1024];
                        int bytesRead = ns.Read(bytes, 0, bytes.Length);
                        string pkt = BitConverter.ToString(bytes, 0, bytesRead);
                        //listBox1.Items.Add(Encoding.ASCII.GetString(bytes, 0, bytesRead));
                        Console.WriteLine(pkt);
                        MyEvent(pkt);
                    }
                    catch (Exception e) 
                    {
                        Console.WriteLine("A Client Exit!");
                        ns.Close();
                        break;
                    }
                }
            }

            public void timeout(object source, System.Timers.ElapsedEventArgs e)
            {
                try
                {
                    byte[] buffer = { 0xFF, 0xFF, 0x0, 0xFF };
                    //byte[] buffer = Encoding.ASCII.GetBytes(" ");
                    ns.Write(buffer, 0, buffer.Length);
                }
                catch (Exception ex) 
                {
                    System.Timers.Timer timer = source as System.Timers.Timer;
                    timer.Enabled = false;
                    timer.Close();
                }
            }

            public void TcpWrite()
            {
                //listBox1.Items.Add("TcpWrite Begin...");
                Console.WriteLine("TcpWrite Begin...");
                try
                {
                    byte[] buffer = { 0xFF, 0xFF, 0x0, 0xFF };
                    //byte[] buffer = Encoding.ASCII.GetBytes(" ");
                    ns.Write(buffer, 0, buffer.Length);
                }
                catch (Exception e) { }
                System.Timers.Timer timer = new System.Timers.Timer(10000);
                timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timeout);
                timer.AutoReset = true;
                timer.Enabled = true;
            }
        }



        public Form1()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            IPAddress serverIp = IPAddress.Parse(textBox1.Text.ToString());
            int port = int.Parse(textBox2.Text.ToString());
            tl = new TcpListener(serverIp,port);
            tl.Start();

            Thread th = new Thread(new ThreadStart(listen));
            th.IsBackground = true;
            th.Start();

            button1.Enabled = false;
        }
        private void listen()
        {
            while (true)
            {
                listBox1.Items.Add("Waiting for connection...");
                //Console.WriteLine("Waiting for connection...");
                Socket sock = tl.AcceptSocket();
                listBox1.Items.Add("Connection accepted.");
                //Console.WriteLine("Connection accepted