1

当我使用 NDK 中的套接字连接时,由于读取调用,我总是得到 -1。(错误)。

我在网上查了好几次,都找不到解决办法。你能帮助我吗?这是我的代码。

void * SocketManager::socketCall(void *ptr) {
        int socket_, n;
        SocketManager *manager = (SocketManager*) ptr;
        while (manager->semaph) ;
        manager->semaph = true;

        bool didConnect = false;
        size_t bufferSize = 32000;
        char buffer[bufferSize];

        const char* value = manager->host.c_str();
        stringstream strValue;
        strValue << value;
        unsigned int host;
        strValue >> host;

        struct sockaddr_in server_address;
        server_address.sin_family = AF_INET;
        server_address.sin_port = htons(10983);
        inet_aton(manager->host.c_str(), &server_address.sin_addr);

        socket_ = socket(AF_INET, SOCK_STREAM, 0);
        if (socket_ < 0) 
            CCLog("ERROR ABRIENDO EL SOCKET");

        n = ::connect(socket_, (struct sockaddr *) &server_address,sizeof(server_address));
        if (n < 0)
            close(socket_);

        manager->onConnect();
        didConnect = true;

        while (!manager->mustDisconnect) {
            n = read(socket_, &buffer, bufferSize);
            if(n<=0)
                break;
            manager->onReadData(buffer, sizeof(buffer));
        }
    if (socket_) {
        close(socket_);
        if (didConnect)
            manager->onDisconnect();
        else
            manager->onTimeout();

    }
    manager->semaph = false;
    manager->mustDisconnect = false;
    return 0;
}
4

0 回答 0