这是采用MODUBS-TCP协议写的PLC通讯
public void Connect()
{
byte[] data = new byte[1024];
string ipadd = serverIP.Text.Trim();//将服务器IP地址存放在字符串 ipadd中
int port = Convert.ToInt32(serverPort.Text.Trim());//将端口号强制为32位整型,存放在port中
//创建一个套接字
IPAddress _ip;
if (!IPAddress.TryParse(ipadd, out _ip))//确定是否是有效的IP
{
ipadd = Dns.GetHostEntry(ipadd).AddressList[0].ToString();//将主机名解析为实例
}
IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);
//newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newclient = new Socket(IPAddress.Parse(ipadd).AddressFamily, SocketType.Stream, ProtocolType.Tcp);
//将套接字与远程服务器地址相连
try
{
newclient.Connect(ie);
connect.Enabled = false;//使连接按钮变成虚的,无法点击
Connected = true;
MessageBox.Show("连接成功");
}
catch (SocketException e)
{
MessageBox.Show("连接服务器失败 " e.Message);
return;
}
ThreadStart myThreaddelegate = new ThreadStart(ReceiveMsg);
myThread = new Thread(myThreaddelegate);
myThread.Start();
timersend.Enabled = true;
}
private void connect_Click_1(object sender, EventArgs e)
{
Connect();
}
private void timersend_Tick(object sender, EventArgs e)
{
int isecond = 5000;//以毫秒为单位
timersend.Interval = isecond;//5秒触发一次
byte[] data = new byte[] { 0x00, 0x0f, 0x00, 0x00, 0x00, 0x06, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01 };//这里我们不讲解04功能码,所以这里用04功能码发送,防止对其他功能码演示的干扰
newclient.Send(data);
}
public void ReceiveMsg()
{
while (true)
{
byte[] data = new byte[1024];
newclient.Receive(data);
int length = data[5];
Byte[] datashow = new byte[length 6];
for (int i = 0; i <= length 5; i )
datashow[i] = data[i];
string stringdata = BitConverter.ToString(datashow);//把数组转换成16进制字符串
if (data[7] == 0x01) { showMsg01(stringdata "\r\n"); };
if (data[7] == 0x02) { showMsg02(stringdata "\r\n"); };
if (data[7] == 0x03) { showMsg03(stringdata "\r\n"); };
if (data[7] == 0x05) { showMsg05(stringdata "\r\n"); };
if (data[7] == 0x06) { showMsg06(stringdata "\r\n"); };
if (data[7] == 0x0F) { showMsg0F(stringdata "\r\n"); };
if (data[7] == 0x10) { showMsg10(stringdata "\r\n"); };
}
}
评论