西门子PCL-1200(tcp)

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Test1
{
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;
using System.Linq;

namespace client
{
class Program
{
//创建Socket连接对象
private static Socket clientSocket = null;
//运行标志位
private static bool isRunning = false;

private static Thread thrClient;

private static byte[] setArray = new byte[243];
static void Main(string[] args)
{
//Console.WriteLine("客户端,请输入Socket连接方式TCP1,UDP:");
//string sendMsg = Console.ReadLine();
//if (sendMsg.Contains("1"))
//{
// TcpClient();
//}
//else
//{
// UdpClient();
//}


byte[] ReceiveData = new byte[243]; //定义一个接收数据的数组
byte[] SendData = new byte[12] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x00, 0x00, 0x01 }; //定义一个发送数据的数组
IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 10, 12 }); //封装IP地址
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //新建一个Socket实例
socket.Connect(ipAddress, 2001); //连接服务器
Console.WriteLine("连接状态:{0}\t", socket.Connected); //显示连接状态
socket.Send(SendData); //发送modbus tcp数据帧
socket.Receive(ReceiveData); //接收modbus tcp数据帧
Console.Write("接收数据帧:\t");
while (true)
{
//接收消息
//定义一个接受缓冲区
byte[] arrMsgRcv = new byte[243];
int length = -1;
try
{
length = socket.Receive(arrMsgRcv);
}
catch (Exception)
{
//MessageBox.Show("异常");
}
if (length > 0)
{
string message1 = string.Join(",", arrMsgRcv.Select(o => o.ToString("X")));
string result = "";
for (int i = 0; i < arrMsgRcv.Length - 10; i++)
{
var ss = BitConverter.ToInt16(arrMsgRcv, i);
result += " " + IPAddress.NetworkToHostOrder(ss);
}

//WriteTxt(message1);
WriteTxt(result);
}
}

Console.ReadLine();


}

public static string ToHexString(byte[] bytes) // 0xae00cf => "AE00CF "

{

string hexString = string.Empty;

if (bytes != null)

{

StringBuilder strB = new StringBuilder();

for (int i = 0; i < bytes.Length; i++)

{

strB.Append(bytes[i].ToString("X2"));

}

hexString = strB.ToString();

}
return hexString;

}

 

public static void TcpClient()
{
Console.WriteLine("按任意键开始连接服务器...");
Console.ReadKey();
//创建一个客户端Socket
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接服务器
clientSocket.Connect(new IPEndPoint(IPAddress.Parse("192.168.10.12"), 2001));
Console.WriteLine("连接服务器成功");
isRunning = true;


while (true)
{
Console.WriteLine("请输入要发送的消息:");
string sendMsg = Console.ReadLine();
if (!string.IsNullOrEmpty(sendMsg))
{
//发送消息
clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(sendMsg));
if (sendMsg == "quit")
{
//关闭连接
clientSocket.Close();
break;
}
get();
//开始线程接受PLC报文
// ReceiveMessage_aaa();
}
}

 

}

public static void get()
{

while (true)
{
//接收消息
byte[] data = new byte[1024*3];
int length = clientSocket.Receive(data);

string receiveMsg = Encoding.Default.GetString(data, 0, length);
var a = ExtentMethod.ToUnicodeString(receiveMsg);
if (receiveMsg == "quit")
{
Console.WriteLine($"客户端输入命令:{receiveMsg},表示客户端断开了连接!");
break;
}
Console.WriteLine("接收到消息:" + receiveMsg);
//WriteTxt(receiveMsg);
}
}


/// <summary>
/// 接受和处理PLC返回的报文
/// </summary>
private static void ReceiveMessage_aaa()
{
while (isRunning == true)
{
//定义一个接受缓冲区
byte[] arrMsgRcv = new byte[243];
int length = -1;
try
{
length = clientSocket.Receive(arrMsgRcv);
}
catch (Exception)
{
throw new Exception();
}
if (length > 0)
{
string message = Encoding.UTF8.GetString(setArray, 0, length);
//WriteTxt(message);
}

}

}

/// <summary>
///
/// </summary>
public static void UdpClient()
{
//做好链接准备
UdpClient client = new UdpClient(); //实例一个端口
IPAddress remoteIP = IPAddress.Parse("192.168.10.10"); //假设发送给这个IP
int remotePort = 2000; //设置端口号
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort); //实例化一个远程端点
Console.WriteLine("请输入发送内容...");
while (true)
{
var sendString = Console.ReadLine();//要发送的数据
if (!string.IsNullOrEmpty(sendString))
{

byte[] sendData = Encoding.Default.GetBytes(sendString);
client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
Console.WriteLine("数据发送成功!");
if (sendString == "quit")
{
client.Close();//关闭连接
break;
}
}
}
}

////方法二:写入到同一个Txt文件
/// <summary>
/// 写入记事本
/// </summary>
/// <param name="log">日志内容</param>
/// <param name="filepath">文件路径(含文件名)</param>
/// <returns></returns>
public static void WriteTxt(string log)
{
string filepath = @"C:\Users\YJM\Desktop\demo";
try
{
string folder = filepath.Substring(0, filepath.LastIndexOf('\\'));
// 创建目录
if (Directory.Exists(folder) == false)
{
Directory.CreateDirectory(folder);
}
// 当文件不存在时创建文件
if (File.Exists(filepath) == false)
{
FileStream fs = File.Create(filepath);
fs.Close();
}
// 写入文件内容
File.AppendAllText(filepath, "【" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + "】" + log + "\r\n", Encoding.Default);

}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

}
}

public static class ExtentMethod
{
public static string ToUnicodeString(this string str)
{
StringBuilder strResult = new StringBuilder();
if (!string.IsNullOrEmpty(str))
{
for (int i = 0; i < str.Length; i++)
{
strResult.Append("\\u");
strResult.Append(((int)str[i]).ToString("x"));
}
}
return strResult.ToString();
}

public static string FromUnicodeString(this string str)
{
//最直接的方法Regex.Unescape(str);
StringBuilder strResult = new StringBuilder();
if (!string.IsNullOrEmpty(str))
{
string[] strlist = str.Replace("\\", "").Split('u');
try
{
for (int i = 1; i < strlist.Length; i++)
{
int charCode = Convert.ToInt32(strlist[i], 16);
strResult.Append((char)charCode);
}
}
catch (FormatException ex)
{
return Regex.Unescape(str);
}
}
return strResult.ToString();
}
}
}

posted @ 2023-06-01 20:53  ITMrRight  阅读(85)  评论(0编辑  收藏  举报