通过tcp套接字发送数据时文件描述符错误

时间:2015-08-14 06:18:54

标签: c++ sockets tcp

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

  

连接失败。错误:文件描述符错误

我错过了什么?

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);
}

1 个答案:

答案 0 :(得分:1)

您是否记得在构造函数中初始化sock-1