C# ModbusTcp协议的使用方法

时间:2022-06-29 05:06:24

 

Tcp客户端:
声明接收TCP协议数据的IP和端口,可以不写,默认是502
private ModbusTcpNet busTcpClient = new ModbusTcpNet("127.0.0.1",503);
写数据,数据是字节数组:byte[] bytes
OperateResult write = busTcpClient.Write("0", bytes);

Tcp服务端(创建一个ModbusService类):
ModbusService mudbusService = new ModbusService();
设置监听端口:
ModbusService.SetPort(nport);
接收到数据后的回传操作(ResultShow是最后一步操作函数,定义成ResultShow(string strResult,byte[] bytes)):
mudbusService.resultCall = ResultShow;
开启服务:
mudbusService.StartServer();

创建的服务端ModbusService类的内容:

C# ModbusTcp协议的使用方法C# ModbusTcp协议的使用方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using HslCommunication.ModBus;
using Log;

namespace XingcPlcModubusServer.ModbusService
{
  public class ModbusService
  {
    private readonly static ModbusService _instance = new ModbusService();
    /// <summary>
    /// 集包modbus服务对象
    /// </summary>
    private HslCommunication.ModBus.ModbusTcpServer jbBusTcpServer;

    public Dictionary<string, MySession> dic_ClientSocket = new Dictionary<string, MySession>();//tcp客户端字典
    private Dictionary<string, Thread> dic_ClientThread = new Dictionary<string, Thread>();//线程字典,每新增一个连接就添加一条线程

    private Socket ClientSocket { get; set; }
    private TcpListener _server;
    private bool mAcceptThreadStop = false;
    private Thread serverThread;
    public static int mPort = 5002;
    public static string mResult = "";
    public Action<string, byte[]> resultCall = null;
    public static int index = 1;

    public static void SetPort(int port)
    {
      mPort = port; 
    }


    //private ICache cache;
    public static ModbusService Instance()
    {
      return _instance;
    }

    /// <summary>
    /// 启动modbus服务
    /// </summary>
    /// <param name="port"></param>
    public int StartServer()
    {
      try
      {
        //cache = new MemoryCacheService();
        //启动集包服务器
        int port = mPort;
        Logger<ModbusService>.Debug("端口:"   port);
        jbBusTcpServer = new HslCommunication.ModBus.ModbusTcpServer();
        jbBusTcpServer.OnDataReceived  = jbBusTcpServer_OnDataReceived;
        jbBusTcpServer.ServerStart(port);
        Logger<ModbusService>.Debug("启动成功:");

      }
      catch (Exception ex)
      {
        Logger<ModbusService>.Error("启动服务失败", ex);
        return -1;
      }
      return 0;
    }


    /// <summary>
    /// 关闭modbus服务
    /// </summary>
    public void CloseServer()
    {
      jbBusTcpServer?.ServerClose();
      qbBusTcpServer?.ServerClose();
      sgBusTcpServer?.ServerClose();
      jcBusTcpServer?.ServerClose();
    }

    private void jbBusTcpServer_OnDataReceived(HslCommunication.ModBus.ModbusTcpServer tcpServer, byte[] modbus)
    {
      //先打印接收到的内容
      //todo:数据协议解析,存储数据库
      //Logger<ModbusService>.Debug("接收集包数据:"   HslCommunication.BasicFramework.SoftBasic.ByteToHexString(modbus, ‘ ‘));
      Logger<ModbusService>.Debug("jiaochadaiDemoReceive:"   index);
      index  ;
      try
      {
        ProcessData(modbus);
      }
      catch (Exception ex)
      {
        Logger<ModbusService>.Error("解析数据失败", ex);
      }
    }


    private void ProcessData(byte[] bytes)
    {
      //Logger<ModbusService>.Debug("ProcessData");

      string str = $"写入的数据:{HslCommunication.BasicFramework.SoftBasic.ByteToHexString(bytes, ‘ ‘)}";//System.Text.Encoding.Default.GetString(bytes);
      mResult = str;
      if(resultCall != null)
      {
        //Logger<ModbusService>.Debug("resultCall:"   mResult);
        resultCall(mResult,bytes);
      }
    }

  }

  /// <summary>
  /// 会话端
  /// </summary>
  public class MySession
  {
    public Socket TcpSocket;//socket对象
    public List<byte> m_Buffer = new List<byte>();//数据缓存区

    public MySession()
    {

    }

    /// <summary>
    /// 发送数据
    /// </summary>
    /// <param name="buf"></param>
    public void Send(byte[] buf)
    {
      if (buf != null)
      {
        TcpSocket.Send(buf);
      }
    }
    /// <summary>
    /// 获取连接的ip
    /// </summary>
    /// <returns></returns>
    public string GetIp()
    {
      IPEndPoint clientipe = (IPEndPoint)TcpSocket.RemoteEndPoint;
      string _ip = clientipe.Address.ToString();
      return _ip;
    }
    /// <summary>
    /// 关闭连接
    /// </summary>
    public void Close()
    {
      TcpSocket.Shutdown(SocketShutdown.Both);
    }
    /// <summary>
    /// 提取正确数据包
    /// </summary>
    public byte[] GetBuffer(int startIndex, int size)
    {
      byte[] buf = new byte[size];
      m_Buffer.CopyTo(startIndex, buf, 0, size);
      m_Buffer.RemoveRange(0, startIndex   size);
      return buf;
    }

    /// <summary>
    /// 添加队列数据
    /// </summary>
    /// <param name="buffer"></param>
    public void AddQueue(byte[] buffer)
    {
      m_Buffer.AddRange(buffer);
    }
    /// <summary>
    /// 清除缓存
    /// </summary>
    public void ClearQueue()
    {
      m_Buffer.Clear();
    }
  }
}
View Code