C#上位机和单片机TCP通信数据传输怎么写代码
时间: 2023-12-03 10:45:01 浏览: 223
在C#上位机和单片机之间进行TCP通信数据传输,需要编写两端的代码。下面是一个简单的示例代码,演示了如何在C#上位机和STM32单片机之间进行TCP通信数据传输。
C#上位机代码:
```c#
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class TcpClientExample
{
public static void Main()
{
try
{
// 创建一个新的TcpClient对象
TcpClient tcpClient = new TcpClient();
// 连接到STM32单片机的IP地址和端口号
tcpClient.Connect(IPAddress.Parse("192.168.1.100"), 1234);
// 获取网络流对象
NetworkStream networkStream = tcpClient.GetStream();
// 发送数据到STM32单片机
byte[] sendBytes = Encoding.UTF8.GetBytes("Hello STM32!");
networkStream.Write(sendBytes, 0, sendBytes.Length);
// 接收STM32单片机的回复
byte[] receiveBytes = new byte[1024];
int receiveCount = networkStream.Read(receiveBytes, 0, receiveBytes.Length);
string receiveString = Encoding.UTF8.GetString(receiveBytes, 0, receiveCount);
Console.WriteLine("Received from STM32: {0}", receiveString);
// 关闭网络流和TcpClient对象
networkStream.Close();
tcpClient.Close();
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex);
}
}
}
```
STM32单片机代码(使用ST的HAL库):
```c
#include "stm32f4xx_hal.h"
#include <string.h>
#define TCP_SERVER_PORT 1234
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART6_UART_Init(void);
static void MX_ETH_Init(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART6_UART_Init();
MX_ETH_Init();
// 创建一个TCP服务器
int serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket < 0) {
Error_Handler();
}
// 绑定服务器IP地址和端口号
struct sockaddr_in serverAddr;
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(TCP_SERVER_PORT);
if (bind(serverSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) {
Error_Handler();
}
// 监听客户端连接请求
if (listen(serverSocket, 1) < 0) {
Error_Handler();
}
while (1) {
// 接受客户端连接请求
struct sockaddr_in clientAddr;
socklen_t clientAddrLen = sizeof(clientAddr);
int clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddr, &clientAddrLen);
if (clientSocket < 0) {
Error_Handler();
}
// 接收客户端发送的数据
char buf[1024];
int rcvCnt = recv(clientSocket, buf, sizeof(buf), 0);
if (rcvCnt > 0) {
printf("Received from C#: %s\n", buf);
// 发送回复给客户端
char *sendStr = "Hello C#!";
int sendCnt = send(clientSocket, sendStr, strlen(sendStr), 0);
if (sendCnt < 0) {
Error_Handler();
}
}
// 关闭客户端连接
close(clientSocket);
}
}
```
注意:以上代码仅供参考,实际使用时需要根据自己的需求进行修改。在实际应用中,还需要考虑网络传输的稳定性和安全性等问题。
阅读全文