TCP和串口间的互相通信(透传)
Tcp作为服务端,接收消息,通过串口发送
private void TcpDataReceive(object clientmsg)
{
string tcpReceiveFormat = "Hex";
Dispatcher.Invoke(new Action(() =>
{
if (TcpSendFormat.IsChecked == true)
{
tcpReceiveFormat = "ASCII";
}
}));
Byte[] bytes = new Byte[1024];
int i;
NetworkStream stream = clientmsg as NetworkStream;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
string msg = "";
byte[] buffer = new byte[i];
buffer = bytes.Take(i).ToArray();
msg += $"[{DateTime.Now.ToString("HH:mm:ss.fff")} ###Rece] ";
if (tcpReceiveFormat.Equals("Hex"))
{
string tempss = "";
foreach (byte b in buffer)
{
msg += $"{b.ToString("X2")} ";
tempss += b.ToString("X2");
}
messageModel.TcpReceNewestMsg = tempss;
}
else if (tcpReceiveFormat.Equals("ASCII"))
{
msg += $"{Encoding.ASCII.GetString(buffer)} ";
messageModel.TcpReceNewestMsg = Encoding.ASCII.GetString(buffer);
}
msg += "\r\n";
messageModel.TcpReceiveMessage += msg;
}
}
private void SerialDataReceive(object sender, SerialDataReceivedEventArgs e)
{
string receiveFormat = "Hex";
Dispatcher.Invoke(new Action(() =>
{
if (SerialSendFormat.IsChecked == true)
{
receiveFormat = "ASCII";
}
}));
int num = serialPort.BytesToRead;
byte[] buffer = new byte[num];
receiveCount += num;
serialPort.Read(buffer, 0, num);
string msg = "";
msg += $"[{DateTime.Now.ToString("HH:mm:ss.fff")} ###Rece] ";
if (receiveFormat.Equals("Hex"))
{
string temps = "";
foreach (byte b in buffer)
{
msg += $"{b.ToString("X2")} ";
temps += b.ToString("X2");
}
messageModel.SerialReceNewestMsg = temps;
}
else if (receiveFormat.Equals("ASCII"))
{
msg += $"{Encoding.ASCII.GetString(buffer)} ";
messageModel.SerialReceNewestMsg = Encoding.ASCII.GetString(buffer);
}
msg += "\r\n";
messageModel.SerialReceiveMessage += msg;
}
源码资源:https://download.csdn.net/download/qq_40397362/85088218``