当前位置: 首页>>代码示例>>C++>>正文


C++ SockAddr::getType方法代码示例

本文整理汇总了C++中SockAddr::getType方法的典型用法代码示例。如果您正苦于以下问题:C++ SockAddr::getType方法的具体用法?C++ SockAddr::getType怎么用?C++ SockAddr::getType使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在SockAddr的用法示例。


在下文中一共展示了SockAddr::getType方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: if

 bool SockAddr::operator<(const SockAddr& r) const {
     if (getType() < r.getType())
         return true;
     else if (getType() > r.getType())
         return false;
     
     if (getPort() < r.getPort())
         return true;
     else if (getPort() > r.getPort())
         return false;
     
     switch (getType()) {
     case AF_INET:  
         return as<sockaddr_in>().sin_addr.s_addr < r.as<sockaddr_in>().sin_addr.s_addr;
     case AF_INET6: 
         return memcmp(as<sockaddr_in6>().sin6_addr.s6_addr, 
                       r.as<sockaddr_in6>().sin6_addr.s6_addr, 
                       sizeof(in6_addr)) < 0;
     case AF_UNIX:  
         return strcmp(as<sockaddr_un>().sun_path, r.as<sockaddr_un>().sun_path) < 0;
     case AF_UNSPEC: 
         return false;
     default: 
         massert(SOCK_FAMILY_UNKNOWN_ERROR, "unsupported address family", false);
     }
     return false;        
 }
开发者ID:EricInBj,项目名称:mongo,代码行数:27,代码来源:sock.cpp

示例2: open

bool UdpEndPoint::open(const SockAddr& sockaddr, 
                        int backlog,
                        auto_ptr<base::net::HandlerCreatorStrategyBase> handler_stg,
                        auto_ptr<base::net::FilterCreatorStrategyBase> sp_filter_stg,
                        ErrorCode* ec)
{
    int fd = ::socket(sockaddr.getType(), SOCK_DGRAM, 0);
    if (-1 == fd)
        RETURN_NET_ERROR_WITH(ec, errno, "addr=" << sockaddr, false);

    ScopedFD spfd(fd);
    if (sockaddr.getType() == AF_UNIX)
    {
        const sockaddr_un& un = sockaddr.as<sockaddr_un>();
        unlink(un.sun_path);   // in case it already exists
    }

    SocketHelper::setNonBlocking(fd, ec);
    SocketHelper::setReusable(fd, ec);

    if (-1 == ::bind(fd, sockaddr.raw(), sockaddr.size()))
        RETURN_NET_ERROR_WITH(ec, errno, "addr=" << sockaddr, false);

    boost::shared_ptr<Handler> newhandler;
	if (0 == sockaddr.getPort())
	{
		struct sockaddr_in addr;
		socklen_t len = sizeof(addr);
		if (-1 == getsockname(fd, (struct sockaddr *)&addr, &len))
	        RETURN_NET_ERROR_WITH(ec, errno, "", false);
		SockAddr setaddr(ntohs(addr.sin_port));
	    handler_stg->create(fd, setaddr, sp_reactor_impl_, newhandler);
	}
	else
	    handler_stg->create(fd, sockaddr, sp_reactor_impl_, newhandler);


    if (!newhandler)
        RETURN_NET_ERROR_WITH(ec, errno, "create handler failed" << sockaddr, false);
    newhandler->setConnected();
    
    if (sp_filter_stg.get())
        newhandler->setFilter(auto_ptr<Filter>(sp_filter_stg->create(false, newhandler.get())));

    HandlerScoper<Handler> handler_scoper(newhandler);
    spfd.release();

    if (!sp_reactor_impl_->registerHandler(newhandler, MASK_READ, ec))
        return false;

    handler_scoper.release();
    setUdpHandler(newhandler);
    return true;
}
开发者ID:haoustc,项目名称:dial,代码行数:54,代码来源:udp_endpoint.cpp

示例3: connect

    bool Socket::connect(SockAddr& remote) {
        _remote = remote;

        _fd = socket(remote.getType(), SOCK_STREAM, 0);
        if ( _fd == INVALID_SOCKET ) {
            LOG(_logLevel) << "ERROR: connect invalid socket " << errnoWithDescription() << endl;
            return false;
        }

        if ( _timeout > 0 ) {
            setTimeout( _timeout );
        }

        static const unsigned int connectTimeoutMillis = 5000;
        ConnectBG bg(_fd, remote);
        bg.go();
        if ( bg.wait(connectTimeoutMillis) ) {
            if ( bg.inError() ) {
                warning() << "Failed to connect to "
                          << _remote.getAddr() << ":" << _remote.getPort()
                          << ", reason: " << bg.getErrnoWithDescription() << endl;
                close();
                return false;
            }
        }
        else {
            // time out the connect
            close();
            bg.wait(); // so bg stays in scope until bg thread terminates
            warning() << "Failed to connect to "
                      << _remote.getAddr() << ":" << _remote.getPort()
                      << " after " << connectTimeoutMillis << " milliseconds, giving up." << endl;
            return false;
        }

        if (remote.getType() != AF_UNIX)
            disableNagle(_fd);

#ifdef SO_NOSIGPIPE
        // ignore SIGPIPE signals on osx, to avoid process exit
        const int one = 1;
        setsockopt( _fd , SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(int));
#endif

        _local = getLocalAddrForBoundSocketFd(_fd);

        _fdCreationMicroSec = curTimeMicros64();

        _awaitingHandshake = false;

        return true;
    }
开发者ID:byterock,项目名称:mongo,代码行数:52,代码来源:sock.cpp

示例4: open

bool Acceptor::open(const SockAddr& sockaddr,
        int backlog,
        auto_ptr<HandlerCreatorStrategyBase> handler_creator_stg,
        auto_ptr<FilterCreatorStrategyBase> filter_stg,
        ErrorCode* ec)
{
    if (!handler_creator_stg.get())
        RETURN_ERROR_WITH(ec, E_NET_CREATE_NEW_HANDLER_FAILED, "addr=" << sockaddr, false);

    int fd = ::socket(sockaddr.getType(), SOCK_STREAM, 0);
    if (-1 == fd)
        RETURN_NET_ERROR_WITH(ec, errno, "addr=" << sockaddr, false);

    ScopedFD spfd(fd);
    if (sockaddr.getType() == AF_UNIX)
    {
        const sockaddr_un& un = sockaddr.as<sockaddr_un>();
        unlink(un.sun_path);   // in case it already exists
    }

    SocketHelper::setNonBlocking(fd, ec);
    SocketHelper::setReusable(fd, ec);

    if (flag_ & OPT_KEEPALIVE)
        SocketHelper::setKeepAlive(fd, ec);
    if (flag_ & OPT_NODELAY)
        SocketHelper::disableNagle(fd, ec);

    if (-1 == ::bind(fd, sockaddr.raw(), sockaddr.size()))
        RETURN_NET_ERROR_WITH(ec, errno, "addr=" << sockaddr, false);

    if (-1 == ::listen(fd, backlog))
        RETURN_NET_ERROR_WITH(ec, errno, "addr=" << sockaddr, false);

    boost::shared_ptr<Handler> newhandler;
    newhandler.reset(new AcceptorHandler(fd, sockaddr, sp_reactor_impl_, handler_creator_stg, filter_stg));

    HandlerScoper<Handler> handler_scoper(newhandler);
    spfd.release();

    if (!sp_reactor_impl_->registerHandler(newhandler, MASK_ACCEPT, ec))
        return false;

    LOG(info, "listen on "<< sockaddr);

    handler_scoper.release();
    setAcceptorHandler(newhandler);
    return true;
}
开发者ID:haoustc,项目名称:server1,代码行数:49,代码来源:acceptor.cpp

示例5: connect

bool Socket::connect(SockAddr& remote) {
    _remote = remote;

    _fd = socket(remote.getType(), SOCK_STREAM, 0);
    if ( _fd == INVALID_SOCKET ) {
        LOG(_logLevel) << "ERROR: connect invalid socket " << errnoWithDescription() << endl;
        return false;
    }

    if ( _timeout > 0 ) {
        setTimeout( _timeout );
    }

    ConnectBG bg(_fd, remote);
    bg.go();
    if ( bg.wait(5000) ) {
        if ( bg.inError() ) {
            close();
            return false;
        }
    }
    else {
        // time out the connect
        close();
        bg.wait(); // so bg stays in scope until bg thread terminates
        return false;
    }

    if (remote.getType() != AF_UNIX)
        disableNagle(_fd);

#ifdef SO_NOSIGPIPE
    // ignore SIGPIPE signals on osx, to avoid process exit
    const int one = 1;
    setsockopt( _fd , SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(int));
#endif

    _local = getLocalAddrForBoundSocketFd(_fd);

    _fdCreationMicroSec = curTimeMicros64();
    return true;
}
开发者ID:nathanielc,项目名称:mongo,代码行数:42,代码来源:sock.cpp

示例6: getPort

bool SockAddr::operator<(const SockAddr& r) const {
    // Address family first
    if (getType() < r.getType()) {
        return true;
    }
    if (getType() > r.getType()) {
        return false;
    }

    // Address second
    int cmp;
    switch (getType()) {
        case AF_INET: {
            const auto laddr = ntohl(as<sockaddr_in>().sin_addr.s_addr);
            const auto raddr = ntohl(r.as<sockaddr_in>().sin_addr.s_addr);
            cmp = (laddr < raddr) ? -1 : (laddr > raddr) ? 1 : 0;
            break;
        }
        case AF_INET6:
            cmp = memcmp(as<sockaddr_in6>().sin6_addr.s6_addr,
                         r.as<sockaddr_in6>().sin6_addr.s6_addr,
                         sizeof(in6_addr));
            break;
        case AF_UNIX:
            cmp = strcmp(as<sockaddr_un>().sun_path, r.as<sockaddr_un>().sun_path);
            break;
        default:
            massert(SOCK_FAMILY_UNKNOWN_ERROR, "unsupported address family", false);
    }
    if (cmp < 0) {
        return true;
    }
    if (cmp > 0) {
        return false;
    }

    // All else equal, compare port
    return getPort() < r.getPort();
}
开发者ID:acmorrow,项目名称:mongo,代码行数:39,代码来源:sockaddr.cpp

示例7: connect

    bool Socket::connect(SockAddr& remote) {
        _remote = remote;

        _fd = socket(remote.getType(), SOCK_STREAM, 0);
        if ( _fd == INVALID_SOCKET ) {
            log(_logLevel) << "ERROR: connect invalid socket " << errnoWithDescription() << endl;
            return false;
        }

        if ( _timeout > 0 ) {
            setSockTimeouts( _fd, _timeout );
        }

        ConnectBG bg(_fd, remote);
        bg.go();
        if ( bg.wait(5000) ) {
            if ( bg.inError() ) {
                close();
                return false;
            }
        }
        else {
            // time out the connect
            close();
            bg.wait(); // so bg stays in scope until bg thread terminates
            return false;
        }

        if (remote.getType() != AF_UNIX)
            disableNagle(_fd);

#ifdef SO_NOSIGPIPE
        // osx
        const int one = 1;
        setsockopt( _fd , SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(int));
#endif

        return true;
    }
开发者ID:tomasv,项目名称:mongo,代码行数:39,代码来源:sock.cpp

示例8: switch

 bool SockAddr::operator==(const SockAddr& r) const {
     if (getType() != r.getType())
         return false;
     
     if (getPort() != r.getPort())
         return false;
     
     switch (getType()) {
     case AF_INET:  return as<sockaddr_in>().sin_addr.s_addr == r.as<sockaddr_in>().sin_addr.s_addr;
     case AF_INET6: return memcmp(as<sockaddr_in6>().sin6_addr.s6_addr, r.as<sockaddr_in6>().sin6_addr.s6_addr, sizeof(in6_addr)) == 0;
     case AF_UNIX:  return strcmp(as<sockaddr_un>().sun_path, r.as<sockaddr_un>().sun_path) == 0;
     case AF_UNSPEC: return true; // assume all unspecified addresses are the same
     default: massert(SOCK_FAMILY_UNKNOWN_ERROR, "unsupported address family", false);
     }
 }
开发者ID:toreboes,项目名称:mongo,代码行数:15,代码来源:sock.cpp

示例9: open

bool Connector::open(const SockAddr& sockaddr, boost::shared_ptr<Handler>* spout, ErrorCode* ec)
{
    if (!sp_creator_stg_.get())
        RETURN_ERROR_WITH(ec, E_NET_CREATE_NEW_HANDLER_FAILED, "addr=" << sockaddr, false);

    int fd = ::socket(sockaddr.getType(), SOCK_STREAM, 0);
    if (-1 == fd)
        RETURN_NET_ERROR_WITH(ec, errno, "addr=" << sockaddr, false);

    ScopedFD spfd(fd);

    SocketHelper::setNonBlocking(fd, ec);
    SocketHelper::setReusable(fd, ec);

    if (flag_ & OPT_KEEPALIVE)
        SocketHelper::setKeepAlive(fd, ec);
    if (flag_ & OPT_NODELAY)
        SocketHelper::disableNagle(fd, ec);

    LOG(info, "connect to " << sockaddr);

    if (-1 == ::connect(fd, sockaddr.raw(), sockaddr.size()))
    {
        if (EINTR != errno && EINPROGRESS != errno)
            RETURN_NET_ERROR_WITH(ec, errno, "addr=" << sockaddr, false);
    }

    boost::shared_ptr<Handler> spnewhandler;
    sp_creator_stg_->create(fd, sockaddr, sp_reactor_impl_, spnewhandler);
    if (!spnewhandler)
        RETURN_ERROR_WITH(ec, E_NET_CREATE_NEW_HANDLER_FAILED, "addr=" << sockaddr, false);

    HandlerScoper<Handler> handler_scoper(spnewhandler);
    spfd.release();

    if (sp_filter_stg_.get())
    	spnewhandler->setFilter(auto_ptr<Filter>(sp_filter_stg_->create(true, spnewhandler.get())));

    if (!sp_reactor_impl_->registerHandler(spnewhandler, MASK_CONNECT|MASK_READ|MASK_WRITE, ec))
        RETURN_IF_ERROR_WITH(ec, false);

    handler_scoper.release();
    if (spout)
        *spout = spnewhandler;
    return true;
}
开发者ID:haoustc,项目名称:dial,代码行数:46,代码来源:connector.cpp

示例10: initAndListen

    void Listener::initAndListen() {
        vector<SockAddr> mine = ipToAddrs(_ip.c_str(), _port);
        vector<int> socks;
        SOCKET maxfd = 0; // needed for select()

        for (vector<SockAddr>::iterator it=mine.begin(), end=mine.end(); it != end; ++it){
            SockAddr& me = *it;

            SOCKET sock = ::socket(me.getType(), SOCK_STREAM, 0);
            if ( sock == INVALID_SOCKET ) {
                log() << "ERROR: listen(): invalid socket? " << errnoWithDescription() << endl;
            }

            if (me.getType() == AF_UNIX){
#if !defined(_WIN32)
                if (unlink(me.getAddr().c_str()) == -1){
                    int x = errno;
                    if (x != ENOENT){
                        log() << "couldn't unlink socket file " << me << errnoWithDescription(x) << " skipping" << endl;
                        continue;
                    }
                }
#endif
            } else if (me.getType() == AF_INET6) {
                // IPv6 can also accept IPv4 connections as mapped addresses (::ffff:127.0.0.1)
                // That causes a conflict if we don't do set it to IPV6_ONLY
                const int one = 1;
                setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*) &one, sizeof(one));
            }

            prebindOptions( sock );
            
            if ( ::bind(sock, me.raw(), me.addressSize) != 0 ) {
                int x = errno;
                log() << "listen(): bind() failed " << errnoWithDescription(x) << " for socket: " << me.toString() << endl;
                if ( x == EADDRINUSE )
                    log() << "  addr already in use" << endl;
                closesocket(sock);
                return;
            }

            if ( ::listen(sock, 128) != 0 ) {
                log() << "listen(): listen() failed " << errnoWithDescription() << endl;
                closesocket(sock);
                return;
            }

            ListeningSockets::get()->add( sock );

            socks.push_back(sock);
            if (sock > maxfd)
                maxfd = sock;
        }

        static long connNumber = 0;
        struct timeval maxSelectTime;
        while ( ! inShutdown() ) {
            fd_set fds[1];
            FD_ZERO(fds);

            for (vector<int>::iterator it=socks.begin(), end=socks.end(); it != end; ++it){
                FD_SET(*it, fds);
            }

            maxSelectTime.tv_sec = 0;
            maxSelectTime.tv_usec = 10000;
            const int ret = select(maxfd+1, fds, NULL, NULL, &maxSelectTime);
            
            if (ret == 0){
                _elapsedTime += maxSelectTime.tv_usec / 1000;
                continue;
            }
            _elapsedTime += ret; // assume 1ms to grab connection. very rough
            
            if (ret < 0){
                int x = errno;
#ifdef EINTR
                if ( x == EINTR ){
                    log() << "select() signal caught, continuing" << endl;
                    continue;
                }
#endif
                if ( ! inShutdown() )
                    log() << "select() failure: ret=" << ret << " " << errnoWithDescription(x) << endl;
                return;
            }

            for (vector<int>::iterator it=socks.begin(), end=socks.end(); it != end; ++it){
                if (! (FD_ISSET(*it, fds)))
                    continue;

                SockAddr from;
                int s = accept(*it, from.raw(), &from.addressSize);
                if ( s < 0 ) {
                    int x = errno; // so no global issues
                    if ( x == ECONNABORTED || x == EBADF ) {
                        log() << "Listener on port " << _port << " aborted" << endl;
                        return;
                    } if ( x == 0 && inShutdown() ){
                        return;   // socket closed
//.........这里部分代码省略.........
开发者ID:erickt,项目名称:mongo,代码行数:101,代码来源:message.cpp

示例11: initAndListen


//.........这里部分代码省略.........
            // both
            _logListen( _port , false );
            _logListen( _sslPort , true );
        }
#else
        _logListen( _port , false );
#endif

        static long connNumber = 0;
        struct timeval maxSelectTime;
        while ( ! inShutdown() ) {
            fd_set fds[1];
            FD_ZERO(fds);
            
            for (vector<SOCKET>::iterator it=socks.begin(), end=socks.end(); it != end; ++it) {
                FD_SET(*it, fds);
            }

            maxSelectTime.tv_sec = 0;
            maxSelectTime.tv_usec = 10000;
            const int ret = select(maxfd+1, fds, NULL, NULL, &maxSelectTime);

            if (ret == 0) {
#if defined(__linux__)
                _elapsedTime += ( 10000 - maxSelectTime.tv_usec ) / 1000;
#else
                _elapsedTime += 10;
#endif
                continue;
            }

            if (ret < 0) {
                int x = errno;
#ifdef EINTR
                if ( x == EINTR ) {
                    log() << "select() signal caught, continuing" << endl;
                    continue;
                }
#endif
                if ( ! inShutdown() )
                    log() << "select() failure: ret=" << ret << " " << errnoWithDescription(x) << endl;
                return;
            }

#if defined(__linux__)
            _elapsedTime += max(ret, (int)(( 10000 - maxSelectTime.tv_usec ) / 1000));
#else
            _elapsedTime += ret; // assume 1ms to grab connection. very rough
#endif

            for (vector<SOCKET>::iterator it=socks.begin(), end=socks.end(); it != end; ++it) {
                if (! (FD_ISSET(*it, fds)))
                    continue;

                SockAddr from;
                int s = accept(*it, from.raw(), &from.addressSize);
                if ( s < 0 ) {
                    int x = errno; // so no global issues
                    if ( x == ECONNABORTED || x == EBADF ) {
                        log() << "Listener on port " << _port << " aborted" << endl;
                        return;
                    }
                    if ( x == 0 && inShutdown() ) {
                        return;   // socket closed
                    }
                    if( !inShutdown() ) {
                        log() << "Listener: accept() returns " << s << " " << errnoWithDescription(x) << endl;
                        if (x == EMFILE || x == ENFILE) {
                            // Connection still in listen queue but we can't accept it yet
                            error() << "Out of file descriptors. Waiting one second before trying to accept more connections." << warnings;
                            sleepsecs(1);
                        }
                    }
                    continue;
                }
                if (from.getType() != AF_UNIX)
                    disableNagle(s);

#ifdef SO_NOSIGPIPE
                // ignore SIGPIPE signals on osx, to avoid process exit
                const int one = 1;
                setsockopt( s , SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(int));
#endif

                if ( _logConnect && ! cmdLine.quiet ){
                    int conns = connTicketHolder.used()+1;
                    const char* word = (conns == 1 ? " connection" : " connections");
                    log() << "connection accepted from " << from.toString() << " #" << ++connNumber << " (" << conns << word << " now open)" << endl;
                }
                
                boost::shared_ptr<Socket> pnewSock( new Socket(s, from) );
#ifdef MONGO_SSL
                if ( _ssl && ( _sslPort == 0 || sslSocks.count(*it) ) ) {
                    pnewSock->secureAccepted( _ssl );
                }
#endif
                accepted( pnewSock );
            }
        }
    }
开发者ID:Desartstudio,项目名称:mongo-nonx86,代码行数:101,代码来源:listen.cpp

示例12: initAndListen


//.........这里部分代码省略.........
                const int mongo_errno = WSAGetLastError();
                error() << "Windows WSAWaitForMultipleEvents returned " 
                    << errnoWithDescription(mongo_errno) << endl;
                fassertFailed(16723);
            }
        
            if (result == WSA_WAIT_TIMEOUT) {
                _elapsedTime += 10;
                continue;
            }
            _elapsedTime += 1; // assume 1ms to grab connection. very rough
            
            // Determine which socket is ready
            DWORD eventIndex = result - WSA_WAIT_EVENT_0;
            WSANETWORKEVENTS networkEvents;            
            // Extract event details, and clear event for next pass
            int status = WSAEnumNetworkEvents(_socks[eventIndex],
                                              events[eventIndex], 
                                              &networkEvents);
            if (status == SOCKET_ERROR) {
                const int mongo_errno = WSAGetLastError();
                error() << "Windows WSAEnumNetworkEvents returned " 
                    << errnoWithDescription(mongo_errno) << endl;
                continue;
            }
            
            if (networkEvents.lNetworkEvents & FD_CLOSE) {              
                log() << "listen socket closed" << endl;
                break;
            }
            
            if (!(networkEvents.lNetworkEvents & FD_ACCEPT)) {
                error() << "Unexpected network event: " << networkEvents.lNetworkEvents << endl;
                continue;
            }
            
            int iec = networkEvents.iErrorCode[FD_ACCEPT_BIT];
            if (iec != 0) {                 
                error() << "Windows socket accept did not work:" << errnoWithDescription(iec) 
                        << endl;
                continue;
            }
            
            status = WSAEventSelect(_socks[eventIndex], NULL, 0);
            if (status == SOCKET_ERROR) {
                const int mongo_errno = WSAGetLastError();
                error() << "Windows WSAEventSelect returned " 
                    << errnoWithDescription(mongo_errno) << endl;
                continue;
            }
            
            disableNonblockingMode(_socks[eventIndex]);
            
            SockAddr from;
            int s = accept(_socks[eventIndex], from.raw(), &from.addressSize);
            if ( s < 0 ) {
                int x = errno; // so no global issues
                if (x == EBADF) {
                    log() << "Port " << _port << " is no longer valid" << endl;
                    continue;
                }
                else if (x == ECONNABORTED) {
                    log() << "Listener on port " << _port << " aborted" << endl;
                    continue;
                }
                if ( x == 0 && inShutdown() ) {
                    return;   // socket closed
                }
                if( !inShutdown() ) {
                    log() << "Listener: accept() returns " << s << " " 
                        << errnoWithDescription(x) << endl;
                    if (x == EMFILE || x == ENFILE) {
                        // Connection still in listen queue but we can't accept it yet
                        error() << "Out of file descriptors. Waiting one second before"
                            " trying to accept more connections." << warnings;
                        sleepsecs(1);
                    }
                }
                continue;
            }
            if (from.getType() != AF_UNIX)
                disableNagle(s);

            long long myConnectionNumber = globalConnectionNumber.addAndFetch(1);

            if (_logConnect && !serverGlobalParams.quiet) {
                int conns = globalTicketHolder.used()+1;
                const char* word = (conns == 1 ? " connection" : " connections");
                log() << "connection accepted from " << from.toString() << " #" << myConnectionNumber << " (" << conns << word << " now open)" << endl;
            }
            
            std::shared_ptr<Socket> pnewSock( new Socket(s, from) );
#ifdef MONGO_CONFIG_SSL
            if (_ssl) {
                pnewSock->secureAccepted(_ssl);
            }
#endif
            accepted( pnewSock , myConnectionNumber );
        }
    }
开发者ID:daveh86,项目名称:mongo,代码行数:101,代码来源:listen.cpp

示例13: connect

bool Socket::connect(SockAddr& remote) {
    _remote = remote;

    _fd = ::socket(remote.getType(), SOCK_STREAM, 0);
    if (_fd == INVALID_SOCKET) {
        networkWarnWithDescription(*this, "socket");
        return false;
    }

    if (!setBlock(_fd, false)) {
        networkWarnWithDescription(*this, "set socket to non-blocking mode");
        return false;
    }

    const Milliseconds connectTimeoutMillis(static_cast<int64_t>(
        _timeout > 0 ? std::min(kMaxConnectTimeoutMS, (_timeout * 1000)) : kMaxConnectTimeoutMS));
    const Date_t expiration = Date_t::now() + connectTimeoutMillis;

    bool connectSucceeded = ::connect(_fd, _remote.raw(), _remote.addressSize) == 0;

    if (!connectSucceeded) {
#ifdef _WIN32
        if (WSAGetLastError() != WSAEWOULDBLOCK) {
            networkWarnWithDescription(*this, "connect");
            return false;
        }
#else
        if (errno != EINTR && errno != EINPROGRESS) {
            networkWarnWithDescription(*this, "connect");
            return false;
        }
#endif

        pollfd pfd;
        pfd.fd = _fd;
        pfd.events = POLLOUT;

        while (true) {
            const auto timeout = std::max(Milliseconds(0), expiration - Date_t::now());

            int pollReturn = socketPoll(&pfd, 1, timeout.count());
#ifdef _WIN32
            if (pollReturn == SOCKET_ERROR) {
                networkWarnWithDescription(*this, "poll");
                return false;
            }
#else
            if (pollReturn == -1) {
                if (errno != EINTR) {
                    networkWarnWithDescription(*this, "poll");
                    return false;
                }

                // EINTR in poll, try again
                continue;
            }
#endif
            // No activity for the full duration of the timeout.
            if (pollReturn == 0) {
                warning() << "Failed to connect to " << _remote.getAddr() << ":"
                          << _remote.getPort() << " after " << connectTimeoutMillis
                          << " milliseconds, giving up.";
                return false;
            }

            // We had a result, see if there's an error on the socket.
            int optVal;
            socklen_t optLen = sizeof(optVal);
            if (::getsockopt(
                    _fd, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&optVal), &optLen) == -1) {
                networkWarnWithDescription(*this, "getsockopt");
                return false;
            }
            if (optVal != 0) {
                networkWarnWithDescription(*this, "checking socket for error after poll", optVal);
                return false;
            }

            // We had activity and we don't have errors on the socket, we're connected.
            break;
        }
    }

    if (!setBlock(_fd, true)) {
        networkWarnWithDescription(*this, "could not set socket to blocking mode");
        return false;
    }

    if (_timeout > 0) {
        setTimeout(_timeout);
    }

    if (remote.getType() != AF_UNIX)
        disableNagle(_fd);

#ifdef SO_NOSIGPIPE
    // ignore SIGPIPE signals on osx, to avoid process exit
    const int one = 1;
    setsockopt(_fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(int));
#endif
//.........这里部分代码省略.........
开发者ID:ksuarz,项目名称:mongo,代码行数:101,代码来源:sock.cpp


注:本文中的SockAddr::getType方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。