C#心跳机制客户端的实现示例

来自:网络
时间:2024-09-10
阅读:

窗体(richTextBox右显示聊天)

C#心跳机制客户端的实现示例

步骤

点击链接按钮
         tcpclient客户端步骤
         1创建客户端对象
         2连接服务器connect
         3创建网络基础流发消息 .write发消息
         4 创建网络基础流接消息 .read接消息
         5 断开连接close()

窗体代码

namespace _02_心跳机制客户端
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        TcpClient client;
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "连接")
            {
                try
                {
                    client = new TcpClient();
                    client.Connect(comboBox1.Text, int.Parse(comboBox2.Text));
                    button1.Text = "断开";
                    StartRead();
                    HeartBeat();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("连接失败");
                }
            }
            else
            {
                client.Close();
                timer.Stop();
                button1.Text = "连接";
            }
        }
        void StartRead()
        {
            byte[] bs = new byte[1024];
            Task.Run(() =>
            {
                try
                {
                    while (true)
                    {
                        int count = client.GetStream().Read(bs,0,bs.Length);
                        string msg = Encoding.UTF8.GetString(bs, 0, count);
                        richTextBox1.Invoke((Action)(() =>
                        {
                            richTextBox1.AppendText(msg + "\t\n");
                        }));
                    }
                }
                catch (Exception ex)
                {

                    button1.Text = "连接";
                }
            });
        }
        Timer timer;
        void HeartBeat()
        {
            timer = new Timer();
            timer.Interval = 10000;
            timer.Tick += Timer_Tick;
            timer.Start();
        }
        private void Timer_Tick(object sender, EventArgs e)
        {
            client.GetStream().Write(new byte[] { 1 }, 0, 1);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            byte[] bs = Encoding.UTF8.GetBytes(textBox1.Text);
            byte[] bs1 = new byte[bs.Length + 1];
            bs1[0] = 0;
            bs.CopyTo(bs1,1);
            client.GetStream().Write(bs1, 0, bs1.Length) ;
        }
    }
}

到此这篇关于C#心跳机制客户端的实现示例的文章就介绍到这了,更多相关C#心跳机制客户端内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持! 

返回顶部
顶部