ModBus——Tcp

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket Sk;
private void Backinfo()
{
while (true)
{
byte[] Inffer = new byte[1024];
int a = Sk.Receive(Inffer);
string Str = BitConverter.ToString(Inffer,0,a);
textBox1.AppendText(DateTime.Now.ToString()+" “+Str+”\r\n");
}
}

    private void Form1_Load(object sender, EventArgs e)
    {
        Control.CheckForIllegalCrossThreadCalls = false;
        Sk = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        IPAddress Plcip = IPAddress.Parse("192.168.0.10");
        int Port = int.Parse("502");
        IPEndPoint Pup = new IPEndPoint(Plcip,Port);
        Sk.Connect(Pup);
        textBox1.AppendText(DateTime.Now.ToString() + "   Modbus_Tcp网络已经连接成功\r\n");

        Thread th = new Thread(Backinfo);
        th.IsBackground = true;
        th.Start();
        textBox1.AppendText(DateTime.Now.ToString() + "   Modbus_Tcp网络返回数据接收线程开启成功\r\n");

    }

    private void button1_Click(object sender, EventArgs e)
    {
        byte[] bb = { 0x97, 0x79, 0x00, 0x00, 0x00, 0x06,0x04,0x05,0x00,0x00,0xff,0x00 };
        Sk.Send(bb);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        byte[] bb = { 0x97, 0x79, 0x00, 0x00, 0x00, 0x06, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00 };
        Sk.Send(bb);
    }

    private void button3_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(textBox3.Text.Trim()))
        {
            MessageBox.Show("振幅数据异常");
            return;
        }
        ushort A = Convert.ToUInt16(textBox3.Text.Trim());
        byte[] AA = BitConverter.GetBytes(A);

        ushort B = Convert.ToUInt16(textBox4.Text.Trim());
        byte[] BB = BitConverter.GetBytes(B);

        Single C = Convert.ToSingle(textBox5.Text.Trim());
        byte[] CC = BitConverter.GetBytes(C);


        byte[] bb = { 0x97, 0x79, 0x00, 0x00, 0x00, 0xF, 0x04, 0x10, 0x00,0x01,0x00,0x04,0x08,
                           AA[1] , AA[0],
                           BB[1], BB[0] ,
                           CC[3],CC[2],CC[1],CC[0]};
   
        Sk.Send(bb);
    }

    private void button4_Click(object sender, EventArgs e)
    {
        byte[] bb = { 0x97, 0x79, 0x00, 0x00, 0x00, 0x06, 0x04, 0x03, 0x00, 0x00, 0x00, 0x03 };
        Sk.Send(bb);
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值