C# WPF上位机实现和下位机TCP通讯

简介: C# WPF上位机实现和下位机TCP通讯下位机使用北京大华程控电源DH1766-1,上位机使用WPF。实现了电压电流实时采集,曲线显示。上午在公司调试成功,手头没有程控电源,使用TCP服务端模拟。昨天写的TCP服务端正好排上用场。

C# WPF上位机实现和下位机TCP通讯
下位机使用北京大华程控电源DH1766-1,上位机使用WPF。实现了电压电流实时采集,曲线显示。上午在公司调试成功,手头没有程控电源,使用TCP服务端模拟。昨天写的TCP服务端正好排上用场。

界面如下:

服务端

服务端实在上篇基础上实现的。需要做如下更改:

复制代码
while (true)

                      {
                          try
                          {
                              byte[] bufferDate = new byte[1024];
                              int realLen = pSocket.Receive(bufferDate);
                              if (realLen <= 0)
                              {
                                  this.Invoke(addTextDelegate, pSocket.RemoteEndPoint.ToString() + "退出\r\n");
                                  socketList.Remove(pSocket);
                                  //客户端退出的时候会发送一个空字节
                                  pSocket.Shutdown(SocketShutdown.Both);
                                  pSocket.Close();
                                  return;
                              }
                              string receiveStr = Encoding.Default.GetString(bufferDate, 0, realLen);
                              switch (receiveStr)
                              {
                                  case "MEAS:VOLTage:ALL?\n":
                                      proxSocket.Send(Encoding.Default.GetBytes(r.Next(16,25).ToString()+ ","+r.Next(16, 25).ToString()+","+ r.Next(16, 25).ToString()));
                                      break;
                                  case "MEAS:CURR:ALL?\n":
                                      proxSocket.Send(Encoding.Default.GetBytes(r.Next(2, 5).ToString() + "," + r.Next(2, 5).ToString() + "," + r.Next(2, 5).ToString()));
                                      break;
                                  default:
                                      break;
                              }
                              this.Invoke(addTextDelegate, receiveStr + "from" + pSocket.RemoteEndPoint.ToString() + "\r\n");
                          }
                          catch (Exception ex)
                          {
                              this.Invoke(addTextDelegate, pSocket.RemoteEndPoint.ToString() + "异常退出\r\n");
                              socketList.Remove(pSocket);
                              pSocket.Shutdown(SocketShutdown.Both);
                              pSocket.Close();
                              return;
                          }
                      }

复制代码
在While循环中加入:

switch (receiveStr)
{
  case "MEAS:VOLTage:ALL?n":
  proxSocket.Send(Encoding.Default.GetBytes(r.Next(16,25).ToString()+ ","+r.Next(16, 25).ToString()+","+ r.Next(16, 25).ToString()));
  break;
  case "MEAS:CURR:ALL?n":
  proxSocket.Send(Encoding.Default.GetBytes(r.Next(2, 5).ToString() + "," + r.Next(2, 5).ToString() + "," + r.Next(2, 5).ToString()));
  break;
  default:
  break;

}

模拟电源,当收到电压查询时,发送16~25中随机数,由于电源是三个通道的,因此发送三个随机数,用逗号隔开。同样收到电流查询,发送2~5之间的随机数。

完整的客户端源码:

复制代码
public partial class Form1 : Form

{
    public Form1()
    {
        InitializeComponent();
        addTextDelegate = new AddTextDelegate(AddText);
    }
    private AddTextDelegate addTextDelegate;
    private List<Socket> socketList = new List<Socket>();

    public delegate void AddTextDelegate(string text);
    private void AddText(string text)
    {
        txtLog.Text += text;
    }

    Random r = new Random();

    private void btnStart_Click(object sender, EventArgs e)
    {
        //参数:寻址方式    传输数据方式  通信协议
        Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

        IPAddress iPAddress = IPAddress.Parse(txtIP.Text);

        //创建EndPoint
        IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, int.Parse(txtPort.Text));

        //绑定端口
        socket.Bind(iPEndPoint);

        //开启侦听
        socket.Listen(10);

        txtLog.Text += "服务启动开启侦听……\r\n";

        Thread thread = new Thread((s) =>
          {
              Socket serSocket = (Socket)s;
              while (true)//不断接收客户端连接
              {
                  this.Invoke(addTextDelegate, "服务正在等待客户端连接……\r\n");

                  //开始接收客户端的连接
                  //阻塞当前线程,等待客户端连接
                  //客户端连接上之后,服务端自动生成一个socket和连接的客端通信
                  Socket proxSocket = serSocket.Accept();

                  this.Invoke(addTextDelegate, "客户端连接成功!\r\n" + proxSocket.RemoteEndPoint.ToString());

                  //proxSocket.Send(Encoding.Default.GetBytes("连接成功!"));

                  socketList.Add(proxSocket);//当前通信的socket放到集合中

                  new Thread(p =>
                  {
                      Socket pSocket = (Socket)p;
                      while (true)
                      {
                          try
                          {
                              byte[] bufferDate = new byte[1024];
                              int realLen = pSocket.Receive(bufferDate);

                              if (realLen <= 0)
                              {
                                  this.Invoke(addTextDelegate, pSocket.RemoteEndPoint.ToString() + "退出\r\n");

                                  socketList.Remove(pSocket);
                                  //客户端退出的时候会发送一个空字节
                                  pSocket.Shutdown(SocketShutdown.Both);
                                  pSocket.Close();

                                  return;
                              }
                              string receiveStr = Encoding.Default.GetString(bufferDate, 0, realLen);
                              switch (receiveStr)
                              {
                                  case "MEAS:VOLTage:ALL?\n":
                                      proxSocket.Send(Encoding.Default.GetBytes(r.Next(16,25).ToString()+ ","+r.Next(16, 25).ToString()+","+ r.Next(16, 25).ToString()));
                                      break;
                                  case "MEAS:CURR:ALL?\n":
                                      proxSocket.Send(Encoding.Default.GetBytes(r.Next(2, 5).ToString() + "," + r.Next(2, 5).ToString() + "," + r.Next(2, 5).ToString()));
                                      break;
                                  default:
                                      break;
                              }
                              this.Invoke(addTextDelegate, receiveStr + "from" + pSocket.RemoteEndPoint.ToString() + "\r\n");
                          }
                          catch (Exception ex)
                          {
                              this.Invoke(addTextDelegate, pSocket.RemoteEndPoint.ToString() + "异常退出\r\n");

                              socketList.Remove(pSocket);
                              pSocket.Shutdown(SocketShutdown.Both);
                              pSocket.Close();
                              return;
                          }
                      }
                  })
                  { IsBackground = true }.Start(proxSocket);
              }
          });
        thread.IsBackground = true;
        thread.Start(socket);
       
    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        string str = txtSend.Text;
        byte[] data = Encoding.Default.GetBytes(str);
        foreach (var socket in socketList)
        {
            if (socket != null && socket.Connected)
            {
                socket.Send(data);
            }
        }
    }
}

复制代码
上位机实现客户端功能。具体如下:

1、字段和属性

public readonly IPEndPoint TagetIPEP;
public bool IsConnected { get; set; } = false;
private Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { /ReceiveTimeout=1000,SendTimeout=1000/};
private Thread recListenThread;
public string ReceiveStr { get; set; }
public byte[] ReceiveByte { get; set; }
TagetIPEP是服务器地址和端口。
IsConnected是连接的状态,这个比较重要,在发送和接收时,都要更加IsConnected进行,并更新IsConnected。
Socket用于和客户端通讯。
recListenThread是监听客户端消息的线程。
ReceiveStr和ReceiveByte用来存储客户端发来的消息。
2、方法函数
连接方法:
复制代码
public bool Connect()

    {
        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                //ReceiveTimeout = 1000,
                //SendTimeout=1000
            };

            //IAsyncResult connResult = socket.BeginConnect(TagetIPEP.Address, TagetIPEP.Port, null, null);
            //connResult.AsyncWaitHandle.WaitOne(5000, true);
            //if (connResult.IsCompleted)
            //{
            socket.Connect(TagetIPEP.Address, TagetIPEP.Port);
            IsConnected = true;
                //开启接收监听

                recListenThread = new Thread(() =>
                {
                    while (true)
                    {
                        try
                        {
                            ReceiveByte = new byte[1024];
                            int realLen = socket.Receive(ReceiveByte);
                            ReceiveStr = Encoding.Default.GetString(ReceiveByte, 0, realLen);
                            ReceiveEvent();
                            if (realLen <= 0)
                            {
                                if (socket != null && socket.Connected)
                                {
                                    //服务器退出
                                    IsConnected = false;
                                    Log.WriteLog("服务器退出!");
                                    socket.Shutdown(SocketShutdown.Both);
                                    socket.Close();
                                    MessageBox.Show("连接断开!");
                                }
                                return;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (socket != null && socket.Connected)
                            {
                                IsConnected = false;
                                Log.WriteLog("服务器异常退出!", ex);
                                socket.Shutdown(SocketShutdown.Both);
                                socket.Close();
                            }
                            return;
                        }
                    }
                })
                { IsBackground = true };
                recListenThread.Start();
                return true;
            //}

        }
        catch (Exception ex)
        {
            Log.WriteLog(TagetIPEP.Address + "连接失败", ex);
        }
        return false;
    }

复制代码
连接函数返回值为bool类型,根据返回值判断连接是否成功连接。这里每次连接都实例化了一个socket,因为在执行socket.close()后,重新打开会失败,而断线重连会经常用到,没有找到更好的方法,干脆重新实例化socket。连接成功后,开启监听服务端消息的线程。这里使用了一个ReceiveEvent()事件,在接收到消息时会触发这个事件,刷新UI界面。

发送方法:

复制代码
public bool Send(string msg)

    {
        byte[] sendMsg = Encoding.Default.GetBytes(msg);
        if (sendMsg.Length > 0&&IsConnected)
        {
            if (socket != null && socket.Connected)
            {
                try
                {
                    socket.Send(sendMsg);
                    return true;
                }
                catch (Exception ex)
                {
                    IsConnected = false;
                    Log.WriteLog("发送数据失败,目标地址" + TagetIPEP.Address, ex);
                }
            }
        }

        return false;

    }

复制代码
关闭方法:

复制代码

public void Close()
    {
        if (socket != null && socket.Connected)
        {
            IsConnected = false;
            recListenThread.Abort();
            Log.WriteLog("关闭连接!");
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
        }
    }

复制代码
在出现异常时调用

消息接收事件:

public event Action ReceiveEvent;

每次接收消息时触发,获取属性ReceiveStr和ReceiveByte的值,刷新UI界面。

完整代码:

复制代码
public class TCPClient

{
    public TCPClient(/*IPEndPoint localIPEP,*/IPEndPoint targetIPEP)
    {
        //socket.Bind(localIPEP);
        TagetIPEP = targetIPEP;
       
    }

    public readonly IPEndPoint TagetIPEP;

    public bool IsConnected { get; set; } = false;

    private Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { /*ReceiveTimeout=1000,SendTimeout=1000*/};

    public bool Connect()
    {
        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                //ReceiveTimeout = 1000,
                //SendTimeout=1000
            };

            //IAsyncResult connResult = socket.BeginConnect(TagetIPEP.Address, TagetIPEP.Port, null, null);
            //connResult.AsyncWaitHandle.WaitOne(5000, true);
            //if (connResult.IsCompleted)
            //{
            socket.Connect(TagetIPEP.Address, TagetIPEP.Port);
            IsConnected = true;
                //开启接收监听

                recListenThread = new Thread(() =>
                {
                    while (true)
                    {
                        try
                        {
                            ReceiveByte = new byte[1024];
                            int realLen = socket.Receive(ReceiveByte);
                            ReceiveStr = Encoding.Default.GetString(ReceiveByte, 0, realLen);
                            ReceiveEvent();
                            if (realLen <= 0)
                            {
                                if (socket != null && socket.Connected)
                                {
                                    //服务器退出
                                    IsConnected = false;
                                    Log.WriteLog("服务器退出!");
                                    socket.Shutdown(SocketShutdown.Both);
                                    socket.Close();
                                    MessageBox.Show("连接断开!");
                                }
                                return;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (socket != null && socket.Connected)
                            {
                                IsConnected = false;
                                Log.WriteLog("服务器异常退出!", ex);
                                socket.Shutdown(SocketShutdown.Both);
                                socket.Close();
                            }
                            return;
                        }
                    }
                })
                { IsBackground = true };
                recListenThread.Start();
                return true;
            //}

        }
        catch (Exception ex)
        {
            Log.WriteLog(TagetIPEP.Address + "连接失败", ex);
        }
        return false;
    }

    public bool Send(string msg)
    {
        byte[] sendMsg = Encoding.Default.GetBytes(msg);
        if (sendMsg.Length > 0&&IsConnected)
        {
            if (socket != null && socket.Connected)
            {
                try
                {
                    socket.Send(sendMsg);
                    return true;
                }
                catch (Exception ex)
                {
                    IsConnected = false;
                    Log.WriteLog("发送数据失败,目标地址" + TagetIPEP.Address, ex);
                }
            }
        }

        return false;

    }

    public event Action ReceiveEvent;

    public string ReceiveStr { get; set; }

    public byte[] ReceiveByte { get; set; }

    public void Close()
    {
        if (socket != null && socket.Connected)
        {
            IsConnected = false;
            recListenThread.Abort();
            Log.WriteLog("关闭连接!");
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
        }
    }

    private Thread recListenThread;

}

复制代码
前台调用,声明Timer定时器,每个一秒触发一次。触发事件如下:

复制代码

    private string flag = "";
    private void QueryTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        Now = DateTime.Now;

        if (!tcp.Send("MEAS:VOLTage:ALL?\n"))
        {
            queryTimer.Enabled = false;
            StartContent = "开始";
            ConnContent = "连接";
            tcp.IsConnected = false;
            MessageBox.Show("查询失败!");
            return;
        }
        flag = "V";
        Thread.Sleep(50);

        if (!tcp.Send("MEAS:CURR:ALL?\n"))
        {
            queryTimer.Enabled = false;
            StartContent = "开始";
            ConnContent = "连接";
            tcp.IsConnected = false;
            MessageBox.Show("查询失败!");
            return;
        }
        flag = "C";

        #region 测试
        //angle += 18;
        //if (angle > 360)
        //{
        //    angle = 18;
        //}

        #endregion

    }

复制代码
刷新UI界面的事件如下:

复制代码
private void Tcp_ReceiveEvent()

    {
        Task.Run(() =>
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                RemoteIP = tcp.TagetIPEP.ToString();
                switch (flag)
                {
                    case "V":
                        VoltValue = Math.Round(Convert.ToDouble(tcp.ReceiveStr.Split(',')[0]), 3);
                        break;
                    case "C":
                        CurrentValue = Math.Round(Convert.ToDouble(tcp.ReceiveStr.Split(',')[0]), 3);
                        break;
                    default:
                        break;
                }

                #region 测试
                //VoltValue = Math.Round(Math.Sin((angle) * pi / 180) * 16 + 16, 3);
                //CurrentValue = Math.Round(Math.Sin((angle) * pi / 180) * 2.5 + 2.5, 3);
                #endregion

                VoltValues.Add(VoltValue);
                CurrentValues.Add(CurrentValue);

                if (VoltValues.Count > 30)
                {
                    VoltValues.RemoveAt(0);
                    CurrentValues.RemoveAt(0);
                }
            });
        });
    }

复制代码
原文地址https://www.cnblogs.com/Samberger/p/10561243.html

相关文章
|
2月前
|
网络协议 网络性能优化 C#
C# 一分钟浅谈:UDP 与 TCP 协议区别
【10月更文挑战第8天】在网络编程中,传输层协议的选择对应用程序的性能和可靠性至关重要。本文介绍了 TCP 和 UDP 两种常用协议的基础概念、区别及应用场景,并通过 C# 代码示例详细说明了如何处理常见的问题和易错点。TCP 适用于需要可靠传输和顺序保证的场景,而 UDP 适用于对延迟敏感且可以容忍一定数据丢失的实时应用。
40 1
C# WPF 中 外部图标引入iconfont,无法正常显示问题 【小白记录】
本文介绍了在C# WPF应用程序中引入外部iconfont图标时可能遇到的显示问题及其解决方法:1) 检查资源路径和引入格式是否正确,确保字体文件引用格式为“#xxxx”,并正确指向字体文件位置;2) 确保图标资源被包含在程序集中,通过设置字体文件的生成操作为Resource(资源)来实现。
C# WPF 中 外部图标引入iconfont,无法正常显示问题 【小白记录】
|
3月前
|
编解码 C# 数据库
C# + WPF 音频播放器 界面优雅,体验良好
【9月更文挑战第18天】这是一个用 C# 和 WPF 实现的音频播放器示例,界面简洁美观,功能丰富。设计包括播放/暂停按钮、进度条、音量控制滑块、歌曲列表和专辑封面显示。功能实现涵盖音频播放、进度条控制、音量调节及歌曲列表管理。通过响应式设计、动画效果、快捷键支持和错误处理,提升用户体验。可根据需求扩展更多功能。
127 3
|
2月前
|
物联网 C#
【C#】简单的蓝牙通讯功能实现
【C#】简单的蓝牙通讯功能实现
43 0
|
4月前
|
C#
C# WPF 将第三方DLL嵌入 exe
C# WPF 将第三方DLL嵌入 exe
90 0
|
4月前
|
前端开发 C# 容器
WPF/C#:实现导航功能
WPF/C#:实现导航功能
80 0
|
4月前
|
设计模式 测试技术 C#
WPF/C#:在WPF中如何实现依赖注入
WPF/C#:在WPF中如何实现依赖注入
77 0
|
4月前
|
前端开发 C# Windows
WPF/C#:如何实现拖拉元素
WPF/C#:如何实现拖拉元素
53 0
|
4月前
|
存储 C# 索引
WPF/C#:BusinessLayerValidation
WPF/C#:BusinessLayerValidation
35 0
|
4月前
|
C#
WPF/C#:数据绑定到方法
WPF/C#:数据绑定到方法
44 0