當前位置: 首頁>>代碼示例>>Python>>正文


Python socket.timeout方法代碼示例

本文整理匯總了Python中socket.timeout方法的典型用法代碼示例。如果您正苦於以下問題:Python socket.timeout方法的具體用法?Python socket.timeout怎麽用?Python socket.timeout使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在socket的用法示例。


在下文中一共展示了socket.timeout方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: connect

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def connect(self):
        if self.is_server:
            log.debug("waiting for client to connect...")
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind(('', self.port))
            s.settimeout(0.1)
            start_time = time.time()
            s.listen(0)
            while True:
                try:
                    conn, _ = s.accept()
                    self.conn = conn
                    break
                except socket.timeout:
                    pass
                if self.timeout > 0 and time.time() - start_time >= self.timeout:
                    s.close()
                    raise RuntimeError("Timeout exceeded (%ds)" % self.timeout)
            self.conn.setblocking(True)
        else:
            log.debug("connecting to server (%s:%d)...", self.ip, self.port)
            self.conn = socket.create_connection((self.ip, self.port), self.timeout) 
開發者ID:blackberry,項目名稱:ALF,代碼行數:24,代碼來源:SockPuppet.py

示例2: jenkins

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def jenkins(url, port):
    try:
        cli_port = False
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        try:
            output = urllib2.urlopen('https://'+url+':'+port+"/jenkins/", context=ctx, timeout=8).info()
            cli_port = int(output['X-Jenkins-CLI-Port'])
        except urllib2.HTTPError, e:
            if e.getcode() == 404:
                try:
                    output = urllib2.urlopen('https://'+url+':'+port, context=ctx, timeout=8).info()
                    cli_port = int(output['X-Jenkins-CLI-Port'])
                except:
                    pass
        except:
            pass 
開發者ID:johndekroon,項目名稱:serializekiller,代碼行數:20,代碼來源:serializekiller.py

示例3: interface_listener_thread

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def interface_listener_thread(s, baddr, port):
    s.settimeout(10)
    mygeneration = generation
    while True:
        try:
            conn, addr = s.accept()
        except socket.timeout:
            if mygeneration == generation:
                continue
            else:
                output('XX', 'INFO: Listener terminating for ' + baddr + ':' + str(port))
                return
        fromto = addr[0] + ':' + str(addr[1]) + '->' + baddr + ':' + str(port)
        #print 'New connection on ' + baddr + ':' + str(port) + ' from ' + addr[0] + ':' + str(addr[1])
        threading.Thread(target=interface_thread , args=(conn, fromto)).start()


# on-demand thread to consume data 
開發者ID:sdn-ixp,項目名稱:iSDX,代碼行數:20,代碼來源:tnode.py

示例4: sendHciCommand

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def sendHciCommand(self, opcode, data, timeout=2):
        """
        Send an arbitrary HCI packet by pushing a send-task into the
        sendQueue. This function blocks until the response is received
        or the timeout expires. The return value is the Payload of the
        HCI Command Complete Event which was received in response to
        the command or None if no response was received within the timeout.
        """

        queue = Queue.Queue(1)
        try:
            self.sendQueue.put((opcode, data, queue), timeout=timeout)
            return queue.get(timeout=timeout)
        except Queue.Empty:
            log.warn("sendHciCommand: waiting for response timed out!")
            return None
        except Queue.Full:
            log.warn("sendHciCommand: send queue is full!")
            return None 
開發者ID:francozappa,項目名稱:knob,代碼行數:21,代碼來源:core.py

示例5: recvPacket

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def recvPacket(self, timeout=None):
        """
        This function polls the recvQueue for the next available HCI
        packet and returns it. The function checks whether it is called
        from the sendThread or any other thread and respectively chooses
        either the sendThreadrecvQueue or the recvQueue.

        The recvQueue is filled by the recvThread. If the queue fills up
        the recvThread empties the queue (unprocessed packets are lost).
        The recvPacket function is meant to receive raw HCI packets in
        a blocking manner. Consider using the registerHciCallback()
        functionality as an alternative which works asynchronously.
        """

        if not self.check_running():
            return None

        try:
            return self.recvQueue.get(timeout=timeout)
        except Queue.Empty:
            return None 
開發者ID:francozappa,項目名稱:knob,代碼行數:23,代碼來源:core.py

示例6: getreview

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def getreview(domain, cityid, activity, reviewid, timeout, maxretries, basepath, force, pause):
    baseurl = 'http://www.tripadvisor.' + domain + '/ShowUserReviews-g'
    reviewurl = '%s%s-d%s-r%s' % (baseurl, cityid, activity, reviewid)

    path = os.sep.join((basepath, domain, str(cityid), str(activity)))
    filename = os.sep.join((path, str(reviewid) + '.html'))
    if force or not os.path.exists(filename):
        htmlpage = download_page(reviewurl, maxretries, timeout, pause)

        if htmlpage is None:
            print('Error downloading the review URL: ' + reviewurl)
        else:
            if not os.path.exists(path):
                os.makedirs(path)

            with codecs.open(filename, mode='w', encoding='utf8') as file:
                file.write(htmlpage.decode('utf-8')) 
開發者ID:aesuli,項目名稱:trip-advisor-crawler,代碼行數:19,代碼來源:trip-advisor-crawler.py

示例7: check

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			server_socket.settimeout(3)
			server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
			client_fake_thread = TCP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
			client_fake_thread.do_check()
			client_fake_thread.communication(True)

			self.cleanup(server_socket)

		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)
		except socket.error as exception:
			if exception.args[0] == 111:
				common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			else:
				common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)

		return 
開發者ID:earthquake,項目名稱:XFLTReaT,代碼行數:26,代碼來源:TCP_generic.py

示例8: __init__

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def __init__(self):
		super(ICMP, self).__init__()
		self.icmp = ICMP_Proto()
		self.ICMP_sequence = 0
		# identifier lottery
		self.ICMP_identifier = int(random.random() * 65535)
		# serverport lottery, not like it matters
		self.ICMP_fake_serverport = int(random.random() * 65535)
		# prefix to make it easier to detect xfl packets
		self.ICMP_prefix = "XFL"
		self.timeout = 2.0
		# if the recv-sent>threshold:
		self.TRACKING_THRESHOLD = 50
		# then we cut back the difference with adjust:
		self.TRACKING_ADJUST = 20

		return 
開發者ID:earthquake,項目名稱:XFLTReaT,代碼行數:19,代碼來源:ICMP.py

示例9: check

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport")))
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.do_check()
			self.communication(True)

		except KeyboardInterrupt:
			self.cleanup()
			raise
		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 
開發者ID:earthquake,項目名稱:XFLTReaT,代碼行數:27,代碼來源:UDP_generic.py

示例10: send

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def send(cmd):
    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    s.settimeout(1)
    flag = False
    for i in range(3):
        try:
            s.sendto(cmd, addr)
            while 1:
                data, a = s.recvfrom(1024)
                if 'ok' in data:
                    flag = True
                    break
        except socket.timeout:
            continue
        except:
            break

        if flag:
            break
    s.close()

    return flag 
開發者ID:Seeed-Studio,項目名稱:wio-cli,代碼行數:24,代碼來源:udp.py

示例11: _http_request

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def _http_request(url, headers=None, time_out=10):
    """Perform an HTTP request and return request"""
    log(0, 'Request URL: {url}', url=url)

    try:
        if headers:
            request = Request(url, headers=headers)
        else:
            request = Request(url)
        req = urlopen(request, timeout=time_out)
        log(0, 'Response code: {code}', code=req.getcode())
        if 400 <= req.getcode() < 600:
            raise HTTPError('HTTP %s Error for url: %s' % (req.getcode(), url), response=req)
    except (HTTPError, URLError) as err:
        log(2, 'Download failed with error {}'.format(err))
        if yesno_dialog(localize(30004), '{line1}\n{line2}'.format(line1=localize(30063), line2=localize(30065))):  # Internet down, try again?
            return _http_request(url, headers, time_out)
        return None

    return req 
開發者ID:emilsvennesson,項目名稱:script.module.inputstreamhelper,代碼行數:22,代碼來源:utils.py

示例12: recvpacket

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def recvpacket(timeout = None):
    global connection
    if connection is None:
        connect()
    #connection.settimeout(timeout)
    #try:
    #    lengthdatum, addr = connection.recvfrom(2)
    #except socket.timeout:
    #    return None
    #connection.settimeout(None)
    #try:
    #    (length, ) = struct.unpack('<H', lengthdatum)
    #except struct.error:
    #    connect()
    #    return None
    #data, addr = connection.recvfrom(length - 2)
    try:
        data, addr = connection.recvfrom(1024)
    except socket.timeout:
        return None
    packet = packetcodec.decode_packet(data)
    if debug:
        print('recvpacket(): ', packet)
    return packet 
開發者ID:sharph,項目名稱:lifx-python,代碼行數:26,代碼來源:network.py

示例13: _raise_timeout

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def _raise_timeout(self, err, url, timeout_value):
        """Is the error actually a timeout? Will raise a ReadTimeout or pass"""

        if isinstance(err, SocketTimeout):
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # See the above comment about EAGAIN in Python 3. In Python 2 we have
        # to specifically catch it and throw the timeout error
        if hasattr(err, 'errno') and err.errno in _blocking_errnos:
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)

        # Catch possible read timeouts thrown as SSL errors. If not the
        # case, rethrow the original. We need to do this because of:
        # http://bugs.python.org/issue10272
        if 'timed out' in str(err) or 'did not complete (read)' in str(err):  # Python 2.6
            raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:18,代碼來源:connectionpool.py

示例14: _new_conn

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def _new_conn(self):
        """ Establish a socket connection and set nodelay settings on it.

        :return: New socket connection.
        """
        extra_kw = {}
        if self.source_address:
            extra_kw['source_address'] = self.source_address

        if self.socket_options:
            extra_kw['socket_options'] = self.socket_options

        try:
            conn = connection.create_connection(
                (self.host, self.port), self.timeout, **extra_kw)

        except SocketTimeout:
            raise ConnectTimeoutError(
                self, "Connection to %s timed out. (connect timeout=%s)" %
                (self.host, self.timeout))

        return conn 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:24,代碼來源:connection.py

示例15: recv

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import timeout [as 別名]
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return b''
            else:
                raise
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b''
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd, wd, ed = select.select(
                [self.socket], [], [], self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv(*args, **kwargs)
        else:
            return data 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:24,代碼來源:pyopenssl.py


注:本文中的socket.timeout方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。