C#心跳机制客户端

窗体(richTextBox右显示聊天)

步骤

点击链接按钮
         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) ;
        }
    }
}

早岁已知世事艰

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值