通过tcp接收byte类型的数据将其转换为uint32_t类型
时间: 2024-02-26 21:56:39 浏览: 66
好的,可以通过如下代码实现:
```c++
#include <iostream>
#include <cstdint>
#include <cstring>
#include <arpa/inet.h>
#include <sys/socket.h>
int main()
{
// 创建socket并连接服务器
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
// 接收数据
uint32_t num;
char buf[4] = {0};
ssize_t recv_len = recv(sockfd, buf, sizeof(buf), 0);
// 将byte类型数据转换为uint32_t类型
if (recv_len == sizeof(num)) {
memcpy(&num, buf, sizeof(num));
num = ntohl(num);
std::cout << "Received number: " << num << std::endl;
} else {
std::cerr << "Error receiving data" << std::endl;
}
// 关闭socket
close(sockfd);
return 0;
}
```
其中,`recv()`函数用于接收数据,`ntohl()`函数用于将网络字节序转换为主机字节序。
阅读全文