基于C#桌面应用程序的常用通信快速实现
串口通信(RS422,RS485,RS232,TTL转USB)
串口连接
using System.IO.Ports;
//连接串口
public void serial_init(SerialPort comm, string portname, int baudrate)
{
comm.DataReceived += comm_DataReceived;//创建和开启串口接收线程
comm.NewLine = "\r\n";
comm.PortName = portname;
comm.BaudRate = baudrate;
try
{
comm.Open();
MessageBox.Show("连接成功");
}
catch (Exception ex)
{
//捕获到异常信息,创建一个新的comm对象,之前的不能用了。
comm = new SerialPort();
//显示异常信息给客户。
MessageBox.Show(ex.Message);
}
}
串口发送
//发送数据,try,catch的好处是当串口操作出现异常时不至于中断程序的运行
public void serial_write_data(SerialPort port_name, byte[] send_data,int start_index,int len)
{
try
{
port_name.Write(send_data, start_index, len);
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
}
串口接收
void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (comm.IsOpen)
{
int n = comm.BytesToRead;
byte[] buf = new byte[n];
comm.Read(buf, 0, n);
}
//在线程中访问应用程序界面资源,将返回数据显示在界面上。textBox1是文本框控件的变量名
this.Invoke((EventHandler)(delegate
{
this.textBox1.AppendText("串口返回:" + BitConverter.ToString(buf));
}));
}
TCP通信
服务端
创建TCP监听
using System.Net;
using System.Net.Sockets;
void Tcp_Connect()
{
// 设置监听的IP和端口
int port = 5032;
//自身的IP
string ipAddress ="192.168.1.4";
// 创建一个TCP监听器
listener = new TcpListener(IPAddress.Parse(ipAddress), port);
Trace.WriteLine($"Server is listening on {ipAddress} : {port}");
// 开始监听
listener.Start();
Thread open_listen = new Thread(() => listen_thread(listener));//带参数传递的线程新建
//TCPThread = new Thread(new ThreadStart(TcpMethod));//不带参数传递的线程新建
open_listen.IsBackground = true;
open_listen.Start();
}
循环监听
void listen_thread(TcpListener listener)
{
try
{
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("连接客户端:" + client.Client.RemoteEndPoint);
Thread clientthread = new Thread(() => TcpMethod(client));//创建TCP接收线程
clientthread.IsBackground = true;
clientthread.Start();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
listener.Stop();
}
数据接收与发送
public void TcpMethod(TcpClient client)
{
NetworkStream stream;
Console.WriteLine("连接客户端:" + client.Client.RemoteEndPoint);
stream = client.GetStream();
stream.ReadTimeout = 10000;
stream.WriteTimeout = 10000;
// 定义缓冲区
byte[] buffer = new byte[1024];
int bytesRead;
while (client.Connected)
{
if (stream.DataAvailable)
{
// 读取客户端发送的数据
try
{
bytesRead = stream.Read(buffer, 0, buffer.Length);
string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Trace.WriteLine($"Received: {data}");
stream.Write(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
Console.WriteLine("数据读取超时,可能客户端连接断开");
Console.WriteLine(ex);
}
}
}
}
客户端
// 连接服务器
TcpClient client = new TcpClient();
client.Connect("192.168.1.4", 5032); // 服务器地址和端口号
try
{
// 获取网络流对象
NetworkStream stream = client.GetStream();
// 数据发送
string messageToSend = "Hello, Server!"; // 要发送的数据
byte[] dataToSend = Encoding.UTF8.GetBytes(messageToSend); // 将字符串转换成字节数组
stream.Write(dataToSend, 0, dataToSend.Length); // 发送数据
// 数据接收
byte[] dataToReceive = new byte[256]; // 接收数据的缓冲区
StringBuilder receivedMessage = new StringBuilder();
int bytesRead;
do
{
bytesRead = stream.Read(dataToReceive, 0, dataToReceive.Length);
receivedMessage.Append(Encoding.UTF8.GetString(dataToReceive, 0, bytesRead));
}
while (stream.DataAvailable);
// 处理接收到的数据
string receivedData = receivedMessage.ToString();
Console.WriteLine("Received: " + receivedData);
}
finally
{
// 关闭连接
client.Close();
}
文件读写
写文件
string test_data_file_name = "";//文件路径
string newData = $"{DateTime.Now.ToString()}" + "," + $"{navi_lati.ToString()}" + "," + $"{navi_long.ToString()}";
using (StreamWriter writer = new StreamWriter(test_data_file_name, true))
{
writer.WriteLine(newData);
}
读文件
string csvFilePath = "";
// 读取文件
List<string[]> data = new List<string[]>();
int counti = 0;
using (StreamReader reader = new StreamReader(csvFilePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] fields = line.Split(',');
data.Add(fields);
}
}
//遍历数据
foreach (string[] rowData in data)
{
counti++;
Trace.WriteLine(counti);
DateTime date = DateTime.Parse(rowData[0]);
navi_lati = float.Parse(rowData[1]);
navi_long = float.Parse(rowData[2]);
}
数据校验
CRC校验(CRC16)
//CRC校验:输入为校验数组,数组长度不包含校验位,输出为带校验位的数组
public Byte[] Crc16(Byte[] input, int start = 0, int len = 0)
{
if (len == 0)
{
len = input.Length - start;
}
int length = start + len;
ushort crc = 0xFFFF;
for (int i = start; i < length; i++)
{
crc ^= input[i];
for (int j = 0; j < 8; j++)
{
if ((crc & 1) > 0)
{
crc = (ushort)((crc >> 1) ^ 0xA001);
}
else
{
crc = (ushort)(crc >> 1);
}
}
}
Byte[] ret = BitConverter.GetBytes(crc);
//Array.Reverse(ret);
Byte[] output = new Byte[length + ret.Length];
input.CopyTo(output, 0);
ret.CopyTo(output, length);
return output;
}
//CRC校验:输入为校验数组,数组长度不包含校验位,输出为两字节的校验位
public Byte[] Crc16_check(Byte[] input, int start = 0, int len = 0)
{
if (len == 0)
{
len = input.Length - start;
}
int length = start + len;
ushort crc = 0xFFFF;
for (int i = start; i < length; i++)
{
crc ^= input[i];
for (int j = 0; j < 8; j++)
{
if ((crc & 1) > 0)
{
crc = (ushort)((crc >> 1) ^ 0xA001);
}
else
{
crc = (ushort)(crc >> 1);
}
}
}
Byte[] ret = BitConverter.GetBytes(crc);
return ret;
}
单字节数据和校验
public byte SB_Sum_check(byte[] check_data, int start_index, int len)
{
byte Sum_data = 0;
for (int i = start_index; i < len; i++)
{
Sum_data += (byte)check_data[i];
}
return Sum_data;
}
双字节数据和校验
public byte[] TB_Sum_check(byte[] check_data, int start_index, int len)
{
byte[] Sum_data = new byte[2];
ushort sumdata = 0;
for (int i = start_index; i < len; i++)
{
sumdata += (byte)check_data[i];
}
return Sum_data=BitConverter.GetBytes(sumdata);
}
位状态判断
public bool bit_status(short data, int bitindex)
{
short mask = (short)(1 << bitindex);
short bitValue = (short)(data & mask);
bool bitStatus = (bitValue != 0);
return bitStatus;
}
public bool bit_status(byte data, int bitindex)
{
short mask = (short)(1 << bitindex);
short bitValue = (short)(data & mask);
bool bitStatus = (bitValue != 0);
return bitStatus;
}