C#应用8——手写ModbusTCP、子线程如何调用UI线程不报错

手写ModbusTCP

ModbusTCP类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace DeltaDemo
{
    public class ModbusTCP
    {
        private Socket socket = null;

        public bool Connect(string ip, int port)
        {
            //实例化Socket
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.Connect(IPAddress.Parse(ip), port);
            }
            catch (Exception)
            {

                return false;
            }
            return true;
        }

        public void DisConnect()
        {
            if (socket != null)
            {
                socket.Close();
            }
        }

        public byte SlaveId { get; set; } = 0x01;
        //读取保持型寄存器
        public short[] ReadKeepReg(ushort start, ushort length)
        {
            //通信五步走

            //拼接
            List<byte> SendCommand = new List<byte>();
            //事务处理标识符
            SendCommand.AddRange(new byte[] { 0x00, 0x00 });
            //协议标识符
            SendCommand.AddRange(new byte[] { 0x00, 0x00 });
            //长度
            SendCommand.AddRange(new byte[] { 0x00, 0x06 });
            //单元表示符
            SendCommand.Add(SlaveId);
            //功能码
            SendCommand.Add(0x03);
            //高位除法,地位求余
            //起始地址
            SendCommand.Add((byte)(start / 256));
            SendCommand.Add((byte)(start % 256));
            //长度
            SendCommand.Add((byte)(length / 256));
            SendCommand.Add((byte)(length % 256));
            //发送
            socket.Send(SendCommand.ToArray());
            //接收
            byte[] buffer = new byte[512];
            int count = socket.Receive(buffer, SocketFlags.None);
            //截取
            byte[] result = new byte[count];
            Array.Copy(buffer, 0, result, 0, count);
            //验证
            if (count == 9 + 2 * length)
            {
                if (result[7] == 0x03 && result[8] == length * 2)
                {
                    //解析
                    short[] data = new short[length];
                    for (int i = 0; i < data.Length; i++)
                    {
						//报错
                        data[i] = BitConverter.ToInt16(new byte[] { result[9 + 2 * i + 1], result[9 + 2 * i] });
                    }
                    return data;
                }
               
            }
            return null;
        }

    }
}

主程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DeltaDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Let's Begin");
            if (modbusTCP.Connect("192.168.1.204", 502))
            {
                Console.WriteLine("Connect Success");
                while (true)
                {
                    short[] val = modbusTCP.ReadKeepReg(0, 1);
                    if (val != null)
                    {
                        Console.WriteLine("D0结果为:" + val[0]);
                    }
                    else
                    {
                        Console.WriteLine("读取失败");
                    }
                    Thread.Sleep(1000);
                }
            }
            else
            {
                Console.WriteLine("Connect Fail");
            }
            Console.ReadLine();




        }

        private static ModbusTCP modbusTCP = new ModbusTCP();
    }
}

子线程如何调用UI线程不报错

C#应用8——手写ModbusTCP、子线程如何调用UI线程不报错_第1张图片

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