gpt4 book ai didi

c++ - 通过 tcp 套接字发送数据时出现错误的文件描述符错误

转载 作者:行者123 更新时间:2023-11-28 06:07:51 25 4
gpt4 key购买 nike

我想创建数据然后发送到服务器。添加新传感器(每个传感器都是一个新网络)后,每个传感器的信息数据应在 Network.cpp 中创建,并使用 client.cpp 发送,我使用继承来使用 Network 类的函数添加到 client 类,反之亦然,但我需要帮助才能正确使用函数来完成我的程序工作。当我运行程序时出现此错误:

connect failed. Error: Bad file descriptor

我错过了什么?

Network.h:

class Network :public client{
public:
Network();
void add(Sensor new_sensor);
virtual ~Network();
private:
vector<Sensor> sensors;
}

网络.cpp:

void Network::add(const client &a,Sensor new_sensor) {
sensors.push_back(new_sensor);
unsigned int Header[2] = {0xe1,0xe2};
uint16_t u16;
u16 = htons(Header[2]);
memcpy(packet + 0, &u16, 2);
unsigned int SensorSn[4] = { 0x1e, 0x25, 0x71, 0x80 };
uint32_t u32;
u32 = htons(SensorSn[4]);
memcpy(packet + 2, &u32, 4);
uint32_t a32;
unsigned int SensorTemp[4] = { 0x00, 0x00, 0x00, 0x23 };
a32 = htons(SensorTemp[4]);
memcpy(packet + 6, &a32, 4);
a.send_data();
}

客户端.h:

class client {
public:
client();
void conn(string, int);
void send_data() const;
string receive(int);
virtual ~client();
private:
int sock;
struct sockaddr_in server_addr;
protected:
char packet[10];
};

}

客户端.cpp:

void client::conn(string address, int port) {
//create socket if it is not already created
if (sock == -1) {
//Create socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
perror("Could not create socket");
}

cout << "Socket created\n" << endl; //doesn't show this line!!!
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(1234);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
while(1){
int m=connect(sock, (struct sockaddr *) &server_addr, sizeof(server_addr));
if (m==-1){
perror("connect failed. Error");
continue;
}
}
cout << "Connected\n"; //doesn't show this line!!!
close(sock);


}
void client::send_data()const {
int n=send(sock, packet, sizeof(packet), 0) ;
if (n==-1){
perror("send failed. Error"); ///my program stop in this line
exit(1);

}
cout << "Data send"<<endl;

close(sock);
}

最佳答案

你还记得在构造函数中将 sock 初始化为 -1 吗?

关于c++ - 通过 tcp 套接字发送数据时出现错误的文件描述符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32005238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com