• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python socket.timeout函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中socket.timeout函数的典型用法代码示例。如果您正苦于以下问题:Python timeout函数的具体用法?Python timeout怎么用?Python timeout使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了timeout函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: connect_ex

 def connect_ex(self, address):
     if self.act_non_blocking:
         return self.fd.connect_ex(address)
     fd = self.fd
     if self.gettimeout() is None:
         while not socket_connect(fd, address):
             try:
                 self._trampoline(fd, write=True)
                 socket_checkerr(fd)
             except socket.error as ex:
                 return get_errno(ex)
             except IOClosed:
                 return errno.EBADFD
     else:
         end = time.time() + self.gettimeout()
         while True:
             try:
                 if socket_connect(fd, address):
                     return 0
                 if time.time() >= end:
                     raise socket.timeout(errno.EAGAIN)
                 self._trampoline(fd, write=True, timeout=end - time.time(),
                            timeout_exc=socket.timeout(errno.EAGAIN))
                 socket_checkerr(fd)
             except socket.error as ex:
                 return get_errno(ex)
             except IOClosed:
                 return errno.EBADFD
开发者ID:SeanHayes,项目名称:eventlet,代码行数:28,代码来源:greenio.py


示例2: recv

    def recv(self, bufsize, flags=0):
        """
        Use select() to simulate a socket timeout without setting the socket
        to non-blocking mode
        """
        timeout = self.__dict__["timeout"]
        con = self.__dict__["conn"]
        (read, write, excpt) = select.select([con], [], [], timeout)
        if not con in read:
            raise socket.timeout((110, "Operation timed out."))

        starttime = time.time()
        while True:
            curtime = time.time()
            if curtime - starttime > timeout:
                raise socket.timeout((110, "Operation timed out."))

            try:
                return con.recv(bufsize, flags)
            except SSL.ZeroReturnError:
                return None
            except SSL.WantReadError:
                time.sleep(0.2)
            except Exception, e:
                if canIgnoreSSLError(e):
                    return None
                else:
                    raise e
开发者ID:lmacken,项目名称:func,代码行数:28,代码来源:SSLConnection.py


示例3: connect

 def connect(self, address):
     if self.act_non_blocking:
         return self.fd.connect(address)
     fd = self.fd
     if self.gettimeout() is None:
         while not socket_connect(fd, address):
             try:
                 self._trampoline(fd, write=True)
             except IOClosed:
                 raise socket.error(errno.EBADFD)
             socket_checkerr(fd)
     else:
         end = time.time() + self.gettimeout()
         while True:
             if socket_connect(fd, address):
                 return
             if time.time() >= end:
                 raise socket.timeout("timed out")
             try:
                 self._trampoline(fd, write=True, timeout=end - time.time(),
                        timeout_exc=socket.timeout("timed out"))
             except IOClosed:
                 # ... we need some workable errno here.
                 raise socket.error(errno.EBADFD)
             socket_checkerr(fd)
开发者ID:SeanHayes,项目名称:eventlet,代码行数:25,代码来源:greenio.py


示例4: _check_timeout

 def _check_timeout(self):
     self._lock()
     conns = self._sock_dict.values()
     self._unlock()
     now = self.get_time()
     # the socking listening is not in _sock_dict, so it'll not be touched
     self._last_checktimeout = now
     for conn in conns:
         inact_time = now - conn.last_ts
         if conn.status_rd == ConnState.IDLE and self._idle_timeout > 0 and inact_time > self._idle_timeout:
             if callable(conn.idle_timeout_cb):
                 conn.error = socket.timeout("idle timeout")
                 conn.idle_timeout_cb(conn, *conn.readable_cb_args)
             self.close_conn(conn)
         elif conn.status_rd == ConnState.TOREAD and self._rw_timeout > 0 and inact_time > self._rw_timeout:
             if callable(conn.read_err_cb):
                 conn.error = socket.timeout("read timeout")
                 self._exec_callback(
                     conn.read_err_cb, (conn,) + conn.read_cb_args, conn.read_tb)
             self.close_conn(conn)
         elif conn.status_wr == ConnState.TOWRITE and self._rw_timeout > 0 and inact_time > self._rw_timeout:
             if callable(conn.write_err_cb):
                 conn.error = socket.timeout("write timeout")
                 self._exec_callback(
                     conn.write_err_cb, (conn,) + conn.write_cb_args, conn.write_tb)
             self.close_conn(conn)
开发者ID:frostyplanet,项目名称:transwarp,代码行数:26,代码来源:socket_engine.py


示例5: blocking_read

    def blocking_read(self, timeout=None):
        read_frame = self.transport.read_frame
        if timeout is None:
            return self.on_inbound_frame(read_frame())

        # XXX use select
        sock = self.sock
        prev = sock.gettimeout()
        if prev != timeout:
            sock.settimeout(timeout)
        try:
            try:
                frame = read_frame()
            except SSLError as exc:
                # http://bugs.python.org/issue10272
                if 'timed out' in str(exc):
                    raise socket.timeout()
                # Non-blocking SSL sockets can throw SSLError
                if 'The operation did not complete' in str(exc):
                    raise socket.timeout()
                raise
            else:
                self.on_inbound_frame(frame)
        finally:
            if prev != timeout:
                sock.settimeout(prev)
开发者ID:makeittotop,项目名称:python-scripts,代码行数:26,代码来源:connection.py


示例6: chk_con

def chk_con(kms):
    #parse kms
    hostname = None
    port = None
    result = None
    ip = None
    ipaddr = None    
    hostname = re.search('https://(.*?):',kms[0],flags=0).group(1)
    logging.info('KMS FQDN : %s' %hostname)
    port = re.search('https://.*:(.*)/',kms[0],flags=0).group(1)
    logging.info ('KMS WebAPI Port : %s' %port)
    #DNS resolve
    try:
        socket.gethostbyname(hostname)
    except :
        logging.error('DNS resolve problem for this KMS server FQDN : %s' %hostname)
        print '!!! DNS resolve issue for FQDN : %s!!!' %hostname
        return (False)
    else :
        result = socket.gethostbyaddr(hostname)
        ip = result[2]        
        ipaddr = ip[0]
        logging.info('KMS IP address : %s' %ipaddr)
    #TCP connect
    socket.timeout(30)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((ipaddr,int(port)))        
    except Exception, e:
        logging.exception('TCP connection error with %s:%d. Exception type is %s' % (ipaddr, int(port), `e`))
        print 'TCP connection error with KMS server %s port %d. Error type %s'% (ipaddr, int(port), `e`)
        return (False)
开发者ID:bobbyc,项目名称:sc-sdk-for-python,代码行数:32,代码来源:policy.py


示例7: test_new_crash_with_fail_retry

    def test_new_crash_with_fail_retry(self):
        config = self._setup_config()
        config.transaction_executor_class = \
            TransactionExecutorWithInfiniteBackoff
        crash_store = RabbitMQCrashStorage(config)

        iterable = [
            ('1', '1', 'crash_id'),
            timeout(),
            timeout(),
            ('2', '2', 'other_id')
        ]
        def an_iterator(queue):
            item =  iterable.pop()
            if isinstance(item, Exception):
                raise item
            return item

        crash_store.rabbitmq.operational_exceptions = (
          timeout,
        )
        crash_store.rabbitmq.return_value.__enter__.return_value  \
            .channel.basic_get = MagicMock(side_effect=an_iterator)

        expected = ('other_id', 'crash_id', )
        for expected, result in zip(expected,  crash_store.new_crashes()):
            eq_(expected, result)
开发者ID:willkg,项目名称:socorro-collector,代码行数:27,代码来源:test_crashstorage.py


示例8: having_timeout

 def having_timeout(self, timeout):
     if timeout is None:
         yield self.sock
     else:
         sock = self.sock
         prev = sock.gettimeout()
         if prev != timeout:
             sock.settimeout(timeout)
         try:
             yield self.sock
         except SSLError as exc:
             if 'timed out' in str(exc):
                 # http://bugs.python.org/issue10272
                 raise socket.timeout()
             elif 'The operation did not complete' in str(exc):
                 # Non-blocking SSL sockets can throw SSLError
                 raise socket.timeout()
             raise
         except socket.error as exc:
             if get_errno(exc) == errno.EWOULDBLOCK:
                 raise socket.timeout()
             raise
         finally:
             if timeout != prev:
                 sock.settimeout(prev)
开发者ID:celery,项目名称:py-amqp,代码行数:25,代码来源:transport.py


示例9: _check_timeout

    def _check_timeout (self):

        self._lock ()
        conns = self._sock_dict.values ()
        self._unlock ()
        now = self.get_time ()
        #the socking listening is not in _sock_dict, so it'll not be touched
        self._last_checktimeout = now
        def __is_timeout (conn):
            inact_time = now - conn.last_ts
            if conn.status == ConnState.IDLE and self._idle_timeout > 0  and inact_time > self._idle_timeout:
                return True
            elif (conn.status == ConnState.TOREAD or conn.status == ConnState.TOWRITE) \
                    and self._rw_timeout > 0 and inact_time > self._rw_timeout:
                return True
            return False
        timeout_list = filter (__is_timeout, conns)
        for conn in timeout_list:
            if conn.status == ConnState.IDLE:
                if callable (conn.idle_timeout_cb):
                    conn.error = socket.timeout ("idle timeout")
                    conn.idle_timeout_cb (conn, *conn.readable_cb_args)
            elif callable(conn.unblock_err_cb):
                conn.error = socket.timeout ("timeout")
                self._exec_callback (conn.unblock_err_cb, (conn,) + conn.unblock_cb_args, conn.unblock_tb)
            self._close_conn (conn)
开发者ID:frostyplanet,项目名称:paxos,代码行数:26,代码来源:socket_engine.py


示例10: _safe_ssl_call

def _safe_ssl_call(suppress_ragged_eofs, sock, call, *args, **kwargs):
    """Wrap the given call with SSL error-trapping."""
    start = time.time()
    while True:
        try:
            return getattr(sock, call)(*args, **kwargs)

        except (ossl.WantReadError, ossl.WantWriteError):
            if select is None:
                if time.time() - start > sock.gettimeout():
                    raise socket.timeout()
                time.sleep(SSL_RETRY)
            elif not select.select([sock], [], [], sock.gettimeout())[0]:
                raise socket.timeout()

        except ossl.SysCallError as e:
            if suppress_ragged_eofs and e.args[0] == (-1, 'Unexpected EOF'):
                return b''
            elif e.args[0] == 0:
                raise SSLEOFError(*e.args)
            raise SSLSysCallError(*e.args)

        except ossl.ZeroReturnError as e:
            raise SSLZeroReturnError(*e.args)

        except ossl.Error as e:
            raise SSLError(*e.args)
开发者ID:rianhunter,项目名称:backports.ssl,代码行数:27,代码来源:core.py


示例11: sendall

    def sendall(self, data, flags=0):
        """
        - Use select() to simulate a socket timeout without setting the socket
            to non-blocking mode.
        - Don't use pyOpenSSL's sendall() either, since it just loops on WantRead
            or WantWrite, consuming 100% CPU, and never times out.
        """
        timeout = self.__dict__["timeout"]
        con = self.__dict__["conn"]
        (read, write, excpt) = select.select([], [con], [], timeout)
        if not con in write:
            raise socket.timeout((110, "Operation timed out."))

        starttime = time.time()
        origlen = len(data)
        sent = -1
        while len(data):
            curtime = time.time()
            if curtime - starttime > timeout:
                raise socket.timeout((110, "Operation timed out."))

            try:
                sent = con.send(data, flags)
            except SSL.SysCallError, e:
                if e[0] == 32:      # Broken Pipe
                    self.close()
                    sent = 0
                else:
                    raise socket.error(e)
            except (SSL.WantWriteError, SSL.WantReadError):
                time.sleep(0.2)
                continue
开发者ID:imcleod,项目名称:koji,代码行数:32,代码来源:SSLConnection.py


示例12: _read

 def _read(self, n, initial=False,
           _errnos=(errno.ENOENT, errno.EAGAIN, errno.EINTR)):
     # According to SSL_read(3), it can at most return 16kb of data.
     # Thus, we use an internal read buffer like TCPTransport._read
     # to get the exact number of bytes wanted.
     recv = self._quick_recv
     rbuf = self._read_buffer
     try:
         while len(rbuf) < n:
             try:
                 s = recv(n - len(rbuf))  # see note above
             except socket.error as exc:
                 # ssl.sock.read may cause a SSLerror without errno
                 # http://bugs.python.org/issue10272
                 if isinstance(exc, SSLError) and 'timed out' in str(exc):
                     raise socket.timeout()
                 # ssl.sock.read may cause ENOENT if the
                 # operation couldn't be performed (Issue celery#1414).
                 if exc.errno in _errnos:
                     if initial and self.raise_on_initial_eintr:
                         raise socket.timeout()
                     continue
                 raise
             if not s:
                 raise IOError('Server unexpectedly closed connection')
             rbuf += s
     except:  # noqa
         self._read_buffer = rbuf
         raise
     result, self._read_buffer = rbuf[:n], rbuf[n:]
     return result
开发者ID:celery,项目名称:py-amqp,代码行数:31,代码来源:transport.py


示例13: recv

    def recv(self, nbytes):
        """
        Receive data from the channel.  The return value is a string
        representing the data received.  The maximum amount of data to be
        received at once is specified by C{nbytes}.  If a string of length zero
        is returned, the channel stream has closed.

        @param nbytes: maximum number of bytes to read.
        @type nbytes: int
        @return: data.
        @rtype: str
        
        @raise socket.timeout: if no data is ready before the timeout set by
            L{settimeout}.
        """
        out = ''
        self.lock.acquire()
        try:
            if len(self.in_buffer) == 0:
                if self.closed or self.eof_received:
                    return out
                # should we block?
                if self.timeout == 0.0:
                    raise socket.timeout()
                # loop here in case we get woken up but a different thread has grabbed everything in the buffer
                timeout = self.timeout
                while (len(self.in_buffer) == 0) and not self.closed and not self.eof_received:
                    then = time.time()
                    self.in_buffer_cv.wait(timeout)
                    if timeout != None:
                        timeout -= time.time() - then
                        if timeout <= 0.0:
                            raise socket.timeout()
            # something in the buffer and we have the lock
            if len(self.in_buffer) <= nbytes:
                out = self.in_buffer
                self.in_buffer = ''
                if self.pipe is not None:
                    # clear the pipe, since no more data is buffered
                    self.pipe.clear()
            else:
                out = self.in_buffer[:nbytes]
                self.in_buffer = self.in_buffer[nbytes:]
            ack = self._check_add_window(len(out))
        finally:
            self.lock.release()

        # no need to hold the channel lock when sending this
        if ack > 0:
            m = Message()
            m.add_byte(chr(MSG_CHANNEL_WINDOW_ADJUST))
            m.add_int(self.remote_chanid)
            m.add_int(ack)
            self.transport._send_user_message(m)

        return out
开发者ID:doomzzju,项目名称:BFSSH,代码行数:56,代码来源:channel.py


示例14: getTime

def getTime():
    TIME_1970 = 2208988800L
    client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    socket.timeout(5)
    data = '\x1b' + 47 * '\0'
    client.sendto(data, (TimeServer, Port))
    data, address = client.recvfrom(1024)
    data_result = struct.unpack('!12I', data)[10]
    data_result -= TIME_1970
    return data_result
开发者ID:sxyy,项目名称:magicCard,代码行数:10,代码来源:commons.py


示例15: HttpPostData

def HttpPostData(postdata):
  socket.timeout(HTTPTIMEOUT)
  try:
    headers = {"Content-type": "application/json", "Accept": "application/json", "Authorization": AUTHTOKEN}
    req = urllib2.Request(SOSSERVER + SOSJSON, postdata, headers)
    response = urllib2.urlopen(req)
    return response.read()
  except urllib2.HTTPError as e:
    print '  error: ' + str(e.code)
    return "ERROR:HTTP " + str(e.code)
开发者ID:walter-snake,项目名称:sos4lml,代码行数:10,代码来源:lml-prepare.py


示例16: test_connection

 def test_connection(self, proxy):
     socket.timeout(30)
     try:
         http = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         http.connect((proxy[0], int(proxy[1])))
         request = "GET /search?output=search&q=habrahabr HTTP/1.1\r\n"
         request += "Host: https://www.google.com\r\n"
         http.send(request.encode("utf-8", "strict"))
         http.recv(65535)
         return True
     except socket.error:
         return False
开发者ID:CLTanuki,项目名称:soc_grabber,代码行数:12,代码来源:proxist.py


示例17: _connect

    def _connect(self):
        self.usage = 0
        try:
            socket.timeout(self._timeout)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
            s.connect((self._host, self._port))

            self._stream = iostream.IOStream(s)
            self._stream.set_close_callback(self._socket_close)

            self._connected = True
        except socket.error, error:
            raise InterfaceError(error)
开发者ID:robert-zaremba,项目名称:mongotor,代码行数:13,代码来源:connection.py


示例18: _recv

 def _recv(self, length):
     if self._timeout:
         if hasattr(select, 'poll'):
             poller = select.poll()
             poller.register(self._sock.fileno())
             ready = poller.poll(self._timeout)
             if not ready:
                 raise socket.timeout("timed out (poll)")
         else:
             ready = select.select([self._sock], [], [], self._timeout)
             if not ready[0]:
                 raise socket.timeout("timed out (select)")
     return self._sock.recv(length)
开发者ID:Cue,项目名称:riak-python-client,代码行数:13,代码来源:pbc.py


示例19: open_socket

def open_socket():
    port = 9999
    mpstate.status.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        mpstate.status.sock.connect(('localhost', port))
        mpstate.status.socket_open = True    
        print("connecting to socket: {}\n".format(port))

    except socket.error:
        if not mpstate.status.sock_failure_data:
            print("socket not availible\n")
        mpstate.status.socket_open = False
    socket.timeout(0.1)
    time.sleep(0.2)
开发者ID:neale,项目名称:MAVProxy,代码行数:14,代码来源:mavproxy.py


示例20: recv_stderr

    def recv_stderr(self, nbytes):
        """
        Receive data from the channel's stderr stream.  Only channels using
        L{exec_command} or L{invoke_shell} without a pty will ever have data
        on the stderr stream.  The return value is a string representing the
        data received.  The maximum amount of data to be received at once is
        specified by C{nbytes}.  If a string of length zero is returned, the
        channel stream has closed.

        @param nbytes: maximum number of bytes to read.
        @type nbytes: int
        @return: data.
        @rtype: str
        
        @raise socket.timeout: if no data is ready before the timeout set by
            L{settimeout}.
        
        @since: 1.1
        """
        out = ''
        self.lock.acquire()
        try:
            if len(self.in_stderr_buffer) == 0:
                if self.closed or self.eof_received:
                    return out
                # should we block?
                if self.timeout == 0.0:
                    raise socket.timeout()
                # loop here in case we get woken up but a different thread has grabbed everything in the buffer
                timeout = self.timeout
                while (len(self.in_stderr_buffer) == 0) and not self.closed and not self.eof_received:
                    then = time.time()
                    self.in_stderr_buffer_cv.wait(timeout)
                    if timeout != None:
                        timeout -= time.time() - then
                        if timeout <= 0.0:
                            raise socket.timeout()
            # something in the buffer and we have the lock
            if len(self.in_stderr_buffer) <= nbytes:
                out = self.in_stderr_buffer
                self.in_stderr_buffer = ''
            else:
                out = self.in_stderr_buffer[:nbytes]
                self.in_stderr_buffer = self.in_stderr_buffer[nbytes:]
            self._check_add_window(len(out))
        finally:
            self.lock.release()
        return out
开发者ID:doomzzju,项目名称:BFSSH,代码行数:48,代码来源:channel.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python socket.write函数代码示例发布时间:2022-05-27
下一篇:
Python socket.ssl函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap