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);
}
}
}