C# 上位机编程之 TcpClient编写

头文件:

using System.Net.Sockets;
using System.Net;

定义变量

private Socket tcpClient;

与服务器连接

 private void BtnConnect_Click(object sender, EventArgs e)
        {

            tcpClient = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

            EndPoint EP = new IPEndPoint(IPAddress.Parse(this.txtIP.Text), int.Parse(this.txtPort.Text));

            try
            {
                tcpClient.Connect(EP);
            }
            catch (Exception ex)
            {
                MessageBox.Show("connect error");
                return;
            }
            MessageBox.Show("connect ok!");


        }

连接成功后,需要进行收发数据

创建一个线程,用于接受数据

using System.Threading;

 private CancellationTokenSource cts = new CancellationTokenSource();
//创建一个线程
  Task.Run(new Action(() =>
                    GetPLCValue()
                    ));

定义线程调用函数 GegPLCValue;

private void GetPLCValue()
        {
            byte[] buffer = new byte[1024];
            int length = -1;
            string str = "";
            while (cts.IsCancellationRequested == false)
            {
                try
                {
                    length = tcpClient.Receive(buffer, SocketFlags.None);
                }
                catch (Exception)
                {
                }
                if (length >0)
                {
                   str = System.Text.Encoding.Default.GetString(buffer);
                    MessageBox.Show("recieved data = "+str);

                }

            }
        }

你可能感兴趣的:(C# 上位机编程之 TcpClient编写)