首页 新闻 会员 周边 捐助

为什么我这个客户端socket程序开一会CUP就100%

0
[已关闭问题] 关闭于 2010-04-23 19:57

namespace client
{
    public partial class Form3 : Form
    {
        private Thread _receiveThread = null;
        private NetworkStream _nws = null;
        private TcpClient clientTcp = null;
        private byte[] cmdBuff = new byte[4096];
        private int bufLen = 0;
        public Form3()
        {
            InitializeComponent();
        }

        private void ReceiveMsg()
        {
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(textBox1.Text.Trim()), Convert.ToInt32(textBox2.Text.Trim()));
            clientTcp = new TcpClient();
            try
            {
                clientTcp.Connect(ipep);
                label4.Text = "已连接";
            }
            catch (SocketException)
            {
                label4.Text = "服务器异常";
            }
            while (true)
            {
                try
                {
                    _nws = clientTcp.GetStream();
                    bufLen = clientTcp.Available;
                    _nws.Read(cmdBuff, 0, bufLen);
                    _nws.Flush();
                    if (bufLen == 0)
                    {
                        continue;
                    }
                    DataObject.Packet packet = (DataObject.Packet)Tool.DeserializeBinary(cmdBuff);
                    richTextBox1.Text = "[" + packet.Name + "]说:" + packet.Say + "\n" + richTextBox1.Text;
                }
                catch
                {
                    label4.Text = "服务器异常";
                    continue;
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            _receiveThread = new Thread(new ThreadStart(ReceiveMsg));
            _receiveThread.Start();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox3.Text.Trim() == "")
                return;
            if (textBox4.Text.Trim() == "")
                return;
            try
            {
                DataObject.Packet packet = new DataObject.Packet() { ID = 1, Name = textBox4.Text.Trim(), Say = textBox3.Text.Trim() };
                byte[] data = Tool.SerializeBinary(packet);
                _nws.Write(data, 0, data.Length);
                _nws.Flush();
            }
            catch
            {
                label4.Text = "服务器异常";
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            clientTcp.Close();
            label4.Text = "未连接";
        }
    }
}

拖鞋王子的主页 拖鞋王子 | 初学一级 | 园豆:38
提问于:2010-04-23 19:21
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册