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) ;
        }
    }
}

早岁已知世事艰

相关推荐
IT_陈寒1 分钟前
Vue这个特性差点让我加班到凌晨,谁懂啊
前端·人工智能·后端
kyriewen5 分钟前
我让AI改一个bug——它偷偷动了5个我没让它碰的地方
前端·javascript·ai编程
遇乐的果园35 分钟前
前端学习笔记-vue加载渲染优化
前端·笔记·学习
心平气和量大福大1 小时前
C#-WPF-Window主窗体
开发语言·c#·wpf
用户985033593281 小时前
OpenLayers 热力图从原理到 Vue 组件一键接入
前端
颜酱1 小时前
01 | 骨架搭建:FastAPI + Vue 跑通第一个 SSE 流式问答
前端·人工智能·后端
白露与泡影1 小时前
Arthas 实战指南:从方法耗时定位到 JVM 变量热修改
服务器·jvm·c#
hoLzwEge1 小时前
解码 IDE 智能提示:jsconfig.json 辅助开发全攻略
前端·前端框架
leoZ2311 小时前
记忆系统与 Agent 定制完全指南(四):自定义 Agent 开发(一)
前端·chrome
慧一居士2 小时前
Element Plus 按需引入的配置使用说明和完整示例
前端·vue.js