我是靠谱客的博主 昏睡小天鹅,这篇文章主要介绍TCP和串口间的互相通信(透传),现在分享给大家,希望可以做个参考。

TCP和串口间的互相通信(透传)

Tcp作为服务端,接收消息,通过串口发送

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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 += "rn"; messageModel.TcpReceiveMessage += msg; } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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 += "rn"; messageModel.SerialReceiveMessage += msg; }

在这里插入图片描述
源码资源:https://download.csdn.net/download/qq_40397362/85088218``

最后

以上就是昏睡小天鹅最近收集整理的关于TCP和串口间的互相通信(透传)的全部内容,更多相关TCP和串口间内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部