美文网首页C#工控机上位机C#编程
C# 上位机编程之 TcpClient编写

C# 上位机编程之 TcpClient编写

作者: 冰冰凉3 | 来源:发表于2021-11-16 01:42 被阅读0次

头文件:

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编写

    本文链接:https://www.haomeiwen.com/subject/aebctrtx.html