C#心跳机制客户端

窗体(richTextBox右显示聊天)

步骤

点击链接按钮

tcpclient客户端步骤

1创建客户端对象

2连接服务器connect

3创建网络基础流发消息 .write发消息

4 创建网络基础流接消息 .read接消息

5 断开连接close()

窗体代码

cs 复制代码
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) ;
        }
    }
}

早岁已知世事艰

相关推荐
纯粹的热爱10 分钟前
🌐 阿里云 Linux 服务器 Let's Encrypt 免费 SSL 证书完整部署指南
前端
北辰alk11 分钟前
Vue3 自定义指令深度解析:从基础到高级应用的完整指南
前端·vue.js
小熊哥72216 分钟前
谈谈最进学习(低延迟)直播项目的坎坷与收获
前端
用户892254118290117 分钟前
游戏框架文档
前端
Holin_浩霖17 分钟前
mini-react 实现function 组件
前端
Yanni4Night17 分钟前
JS 引擎赛道中的 Rust 角色
前端·javascript
欧阳的棉花糖19 分钟前
纯Monorepo vs 混合式Monorepo
前端·架构
北辰alk19 分钟前
Vue3 异步组件深度解析:提升大型应用性能与用户体验的完整指南
前端·vue.js
MM_MS24 分钟前
C#小案例-->汽车租聘系统计价功能
c#·汽车·简单工厂模式·抽象工厂模式·visual studio
MM_MS1 小时前
WinForm+C#小案例--->爱心跑马灯演示
开发语言·c#·visual studio