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

早岁已知世事艰

相关推荐
林杜雨都3 小时前
Action和Func
开发语言·c#
吕了了3 小时前
85 微PE吕了了修改版--更新!
运维·windows·电脑·系统
工程师0073 小时前
TPL如何自动调整执行效率
c#·tpl
PineappleCoder3 小时前
还在重复下载资源?HTTP 缓存让二次访问 “零请求”,用户体验翻倍
前端·性能优化
拉不动的猪3 小时前
webpack编译中为什么不建议load替换ast中节点删除consolg.log
前端·javascript·webpack
李姆斯4 小时前
Agent时代下,ToB前端的UI和交互会往哪走?
前端·agent·交互设计
修炼者4 小时前
Windows如何自定义任何窗口置顶
windows
源码获取_wx:Fegn08954 小时前
基于springboot + vue健身房管理系统
java·开发语言·前端·vue.js·spring boot·后端·spring
闲谈共视4 小时前
基于去中心化社交与AI智能服务的Web钱包商业开发的可行性
前端·人工智能·去中心化·区块链
CreasyChan4 小时前
C# 反射详解
开发语言·前端·windows·unity·c#·游戏开发