使用SimpleTcp.dll完成TCP通信

首先使用的的NuGet下载SimpleTcp,之后可以使用该库完成TCP连接,断开,发送,发送并返回相应,接收事件。本文围绕上述常用的操作进行编写程序。

下载的SimpleTcp如下图:

使用SimpleTcp.dll完成TCP通信_第1张图片

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SimpleTCP;

namespace SimpleTCPTest
{
    public partial class Form1 : Form
    {
        SimpleTcpClient client;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                client = new SimpleTcpClient().Connect(txtIPAddress.Text, int.Parse(txtServerPort.Text));
                btnConnect.Enabled = false;
                //直接启动数据接收的事件
                client.DataReceived += (w, msg) =>
                {

                    this.txtReceiveData.Invoke(new Action(() => { txtReceiveData.Text = msg.MessageString; }));
                };
            }
            catch (Exception ex)
            {
                btnConnect.Enabled = true ;

                MessageBox.Show(ex.Message);
            }
   
        }

        private void btnDisConnect_Click(object sender, EventArgs e)
        {
            try
            {
                client.Disconnect();
                btnConnect.Enabled = true;
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            client.Write(txtSendData.Text);
        }
    }
}


代码下载链接:https://download.csdn.net/download/yue1453544229/10393693

你可能感兴趣的:(C#)