WinForm之TCP客户端通讯

目录

[一 设计界面](#一 设计界面)

[二 后台代码](#二 后台代码)


一 设计界面

二 后台代码

cs 复制代码
using System.Net.Sockets;
using System.Text;

namespace TCP网络客户端通讯
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        TcpClient tcpClient = new TcpClient();

        private void connect_Click(object sender, EventArgs e)
        {
            if (!tcpClient.Connected)
            {
                tcpClient.Connect(IP.Text, int.Parse(PORT.Text));

                //开启线程一直读取数据
                Task.Run(() =>
                {
                    while (true)
                    {
                        NetworkStream networkStream = tcpClient.GetStream();
                        if (networkStream != null)
                        {
                            byte[] datas = new byte[1024];
                            networkStream.Read(datas, 0, datas.Length);
                            this.BeginInvoke(new Action(() =>
                            {
                                log.Text = Encoding.UTF8.GetString(datas);
                            }));
                        }
                    }
                });
            }
        }

        private void send_Click(object sender, EventArgs e)
        {
            NetworkStream networkStream = tcpClient.GetStream();
            if (networkStream != null)
            {
                byte[] datas = Encoding.UTF8.GetBytes(log.Text);
                networkStream.Write(datas, 0, datas.Length);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            IP.Text = "127.0.0.1";
            PORT.Text = "8899";
        }
    }
}

设计器自动生成代码:

cs 复制代码
namespace TCP网络客户端通讯
{
    partial class Form1
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            label1 = new Label();
            label2 = new Label();
            IP = new TextBox();
            PORT = new TextBox();
            connect = new Button();
            log = new RichTextBox();
            send = new Button();
            SuspendLayout();
            // 
            // label1
            // 
            label1.AutoSize = true;
            label1.Location = new Point(32, 52);
            label1.Name = "label1";
            label1.Size = new Size(22, 20);
            label1.TabIndex = 0;
            label1.Text = "IP";
            // 
            // label2
            // 
            label2.AutoSize = true;
            label2.Location = new Point(32, 113);
            label2.Name = "label2";
            label2.Size = new Size(39, 20);
            label2.TabIndex = 1;
            label2.Text = "端口";
            // 
            // IP
            // 
            IP.Location = new Point(103, 52);
            IP.Name = "IP";
            IP.Size = new Size(125, 27);
            IP.TabIndex = 2;
            // 
            // PORT
            // 
            PORT.Location = new Point(103, 110);
            PORT.Name = "PORT";
            PORT.Size = new Size(125, 27);
            PORT.TabIndex = 3;
            // 
            // connect
            // 
            connect.Location = new Point(32, 185);
            connect.Name = "connect";
            connect.Size = new Size(196, 29);
            connect.TabIndex = 4;
            connect.Text = "连接";
            connect.UseVisualStyleBackColor = true;
            connect.Click += connect_Click;
            // 
            // log
            // 
            log.Location = new Point(32, 258);
            log.Name = "log";
            log.Size = new Size(196, 134);
            log.TabIndex = 5;
            log.Text = "";
            // 
            // send
            // 
            send.Location = new Point(32, 416);
            send.Name = "send";
            send.Size = new Size(196, 29);
            send.TabIndex = 6;
            send.Text = "发送数据";
            send.UseVisualStyleBackColor = true;
            send.Click += send_Click;
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(9F, 20F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(391, 497);
            Controls.Add(send);
            Controls.Add(log);
            Controls.Add(connect);
            Controls.Add(PORT);
            Controls.Add(IP);
            Controls.Add(label2);
            Controls.Add(label1);
            MaximizeBox = false;
            Name = "Form1";
            Text = "TCP客户端通讯";
            Load += Form1_Load;
            ResumeLayout(false);
            PerformLayout();
        }

        #endregion

        private Label label1;
        private Label label2;
        private TextBox IP;
        private TextBox PORT;
        private Button connect;
        private RichTextBox log;
        private Button send;
    }
}
相关推荐
wilsonzane2 分钟前
Mongodb性能优化方法
数据库·mongodb
InterestingFigure7 分钟前
Java 使用sql查询mongodb
java·开发语言·数据库·sql·mongodb
吹吹晚风-13 分钟前
深入Django(三)
数据库·django·sqlite
xyh200418 分钟前
python 10个自动化脚本
数据库·python·自动化
W Y25 分钟前
【架构-20】死锁
java·数据库·架构··死锁·银行家算法
just-julie29 分钟前
Redis 分布式集群方案 Cluster
数据库·redis·分布式
泡芙冰淇淋ya31 分钟前
【redis】redis知识点学习目录整理及简介
数据库·redis·学习
zengson_g39 分钟前
如何处理 PostgreSQL 中由于表锁定导致的并发访问问题?
数据库·postgresql
啊取名真困难1 小时前
WhatsApp机器人:提升客户服务效率的自动化工具
数据库·机器人·自动化
深鱼~1 小时前
Linux系统部署MongoDB开源文档型数据库并实现无公网IP远程访问
linux·数据库·mongodb