简体   繁体   中英

Bad file descriptor error while sending data through tcp socket

I want to create data and then send to server . Data from information on each sensor should create in Network.cpp after new sensor was added (each sensor is an new network) and send with client.cpp , I use inheritance to use function add of Network class to client class or vice versa but I need help to use function correctly for my program work. When I run program I get this error:

connect failed. Error: Bad file descriptor

What am I missing?

Network.h:

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

Network.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();
}

client.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];
};

} 

client.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吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM