在前面的文章中简单介绍过通过Socket套接字读取PLC中的数据,并解析出获取的数据。下面将介绍通过Socket套接字向施耐德PLC中写数据的方法(其实大同小异,只是功能码稍有不同)。
下面测试的是通过Socket套接字应用06功能码写单个保持寄存器的方法
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace CXFW
{
public partial class Form1 : Form
{
public System.Threading.Timer timertx1;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
TimerCallback callback = new TimerCallback(this.check);
timertx1 = new System.Threading.Timer(callback, null, 1000, 1000);
}
private void check(object state)
{
byte[] ww = BitConverter.GetBytes(Convert.ToSingle(80.9));
byte a1 = ww[0];
byte a2 = ww[1];
byte a3 = ww[2];
byte a4 = ww[3];
timertx1.Change(Timeout.Infinite, Timeout.Infinite);
byte[] bytOut1 = new byte[12];
bytOut1[0] = 0X00;
bytOut1[1] = 0X00;
bytOut1[2] = 0X00;
bytOut1[3] = 0X00;
bytOut1[4] = 0X00;
bytOut1[5] = 0X06;
bytOut1[6] = 0X01;
bytOut1[7] = 0X06;
bytOut1[8] = 0X0F;
bytOut1[9] = 0XA1;
bytOut1[10] = a2;
bytOut1[11] = a1;
byte[] bytOut2 = new byte[12];
bytOut2[0] = 0X00;
bytOut2[1] = 0X00;
bytOut2[2] = 0X00;
bytOut2[3] = 0X00;
bytOut2[4] = 0X00;
bytOut2[5] = 0X06;
bytOut2[6] = 0X01;
bytOut2[7] = 0X06;
bytOut2[8] = 0X0F;
bytOut2[9] = 0XA2;
bytOut2[10] = a4;
bytOut2[11] = a3;
string host = "200.0.0.81";
int port = 502;
IPAddress ip = IPAddress.Parse(host);//
//组合出远程终结点
IPEndPoint hostEP = new IPEndPoint(ip, port);
//创建Socket 实例
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SendTimeout = 1000;
socket.ReceiveTimeout = 2000;
try
{
//尝试连接
socket.Connect(hostEP); //建立与远程主机的联接
}
catch (Exception se)
{
}
if (socket.Connected == true)
{
socket.Send(bytOut1, 12,0);
}
Thread.Sleep(800);
if (socket.Connected == true)
{
socket.Send(bytOut2, 12, 0);
}
Thread.Sleep(800);
try
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
catch (Exception)
{
}
timertx1.Change(1000, 1000);
}
}
}