我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用socket.timeout()。
def wait(self, timeout=None): """Must be used with 'yield' as 'yield event.wait()' . """ if self._flag: raise StopIteration(True) if not self._scheduler: self._scheduler = Pycos.scheduler() task = Pycos.cur_task(self._scheduler) if timeout is not None: if timeout <= 0: raise StopIteration(False) self._waitlist.append(task) if (yield task._await_(timeout)) is None: try: self._waitlist.remove(task) except ValueError: pass raise StopIteration(False) else: raise StopIteration(True)
def close_peer(self, location, timeout=MsgTimeout): """Must be used with 'yield', as 'yield scheduler.close_peer("loc")'. Close peer at 'location'. """ if isinstance(location, Location): _Peer._lock.acquire() peer = _Peer.peers.get((location.addr, location.port), None) _Peer._lock.release() if peer: def sys_proc(peer, timeout, done, task=None): yield _Peer.close_peer(peer, timeout=timeout, task=task) done.set() event = Event() SysTask(sys_proc, peer, timeout, event) yield event.wait()
def del_file(self, location, file, dir=None, timeout=None): """Must be used with 'yield' as 'loc = yield scheduler.del_file(location, "file1")'. Delete 'file' from peer at 'location'. 'dir' must be same as that used for 'send_file'. """ if isinstance(dir, basestring) and dir: dir = dir.strip() # reject absolute path for dir if os.path.join(os.sep, dir) == dir: raise StopIteration(-1) kwargs = {'file': os.path.basename(file), 'dir': dir} req = _NetRequest('del_file', kwargs=kwargs, dst=location, timeout=timeout) reply = yield _Peer._sync_reply(req) if reply is None: reply = -1 raise StopIteration(reply)
def locate(name, location=None, timeout=None): """Must be used with 'yield' as 'rti = yield RTI.locate("name")'. Returns RTI instance to registered RTI at a remote peer so its method can be used to execute tasks at that peer. If 'location' is given, RTI is looked up at that specific peer; otherwise, all known peers are queried for given name. """ if not RTI._pycos: RTI._pycos = Pycos.instance() req = _NetRequest('locate_rti', kwargs={'name': name}, dst=location, timeout=timeout) req.event = Event() req_id = id(req) RTI._pycos._lock.acquire() RTI._pycos._pending_reqs[req_id] = req RTI._pycos._lock.release() _Peer.send_req_to(req, location) if (yield req.event.wait(timeout)) is False: req.reply = None rti = req.reply RTI._pycos._lock.acquire() RTI._pycos._pending_reqs.pop(req_id, None) RTI._pycos._lock.release() raise StopIteration(rti)
def monitor(self, task, timeout=MsgTimeout): """Must be used with 'yeild' as 'reply = yield rti.monitor(task)'. Install 'task' (a Task instance) as monitor for tasks created; i.e., 'task' receives MonitorException messages. If call is successful, the result is 0. """ if not isinstance(task, Task) and monitor is not None: raise StopIteration(-1) if self._mid: mid = self._mid else: mid = RTI._pycos._location req = _NetRequest('rti_monitor', kwargs={'name': self._name, 'monitor': task, 'mid': mid}, dst=self._location, timeout=timeout) reply = yield _Peer._sync_reply(req) if reply == 0: self._mid = mid raise StopIteration(reply)
def __call__(self, *args, **kwargs): """Must be used with 'yeild' as 'rtask = yield rti(*args, **kwargs)'. Run RTI (method at remote location) with args and kwargs. Both args and kwargs must be serializable. Result is (remote) Task instance if call succeeds, otherwise it is None. """ req = _NetRequest('run_rti', kwargs={'name': self._name, 'args': args, 'kwargs': kwargs, 'mid': self._mid}, dst=self._location, timeout=MsgTimeout) reply = yield _Peer._sync_reply(req) if isinstance(reply, Task): raise StopIteration(reply) elif reply is None: raise StopIteration(None) else: raise Exception(reply)
def _timed_out(self): if self._rsock and self._rsock.type & socket.SOCK_STREAM: if self._read_overlap or self._write_overlap: win32file.CancelIo(self._fileno) if self._read_task: if self._rsock and self._rsock.type & socket.SOCK_DGRAM: self._notifier.clear(self, _AsyncPoller._Read) self._read_fn = None self._read_task.throw(socket.timeout('timed out')) self._read_result = self._read_task = None if self._write_task: if self._rsock and self._rsock.type & socket.SOCK_DGRAM: self._notifier.clear(self, _AsyncPoller._Write) self._write_fn = None self._write_task.throw(socket.timeout('timed out')) self._write_result = self._write_task = None
def send(self, message): """May be used with 'yield'. Sends 'message' to task. If task is currently waiting with 'receive', it is resumed with 'message'. Otherwise, 'message' is queued so that next receive call will return message. Can also be used on remotely running tasks. """ if self._location: request = _NetRequest('send', kwargs={'message': message, 'name': self._name, 'task': self._id}, dst=self._location, timeout=MsgTimeout) # request is queued for asynchronous processing if _Peer.send_req(request) != 0: logger.warning('remote task at %s may not be valid', self._location) return -1 else: return 0 else: return self._scheduler._resume(self, message, Pycos._AwaitMsg_)
def deliver(self, message, timeout=None): """Must be used with 'yield' as 'yield task.deliver(message)'. Can also be used on remotely running tasks. Return value indicates status of delivering the message: If it is 1, then message has been delivered, if it is 0, it couldn't be delivered before timeout, and if it is < 0, then the (remote) task is not valid. """ if self._location: request = _NetRequest('deliver', kwargs={'message': message, 'name': self._name, 'task': self._id}, dst=self._location, timeout=timeout) request.reply = -1 reply = yield _Peer._sync_reply(request, alarm_value=0) if reply is None: reply = -1 # if reply < 0: # logger.warning('remote task at %s may not be valid', self._location) else: reply = self._scheduler._resume(self, message, Pycos._AwaitMsg_) if reply == 0: reply = 1 raise StopIteration(reply)
def value(self, timeout=None): """Get last value 'yield'ed / value of StopIteration of task. NB: This method should _not_ be called from a task! This method is meant for main thread in the user program to wait for (main) task(s) it creates. Once task stops (finishes) executing, the last value is returned. """ value = None self._scheduler._lock.acquire() if self._complete is None: self._complete = threading.Event() self._scheduler._lock.release() if self._complete.wait(timeout=timeout) is True: value = self._value elif self._complete == 0: self._scheduler._lock.release() value = self._value else: self._scheduler._lock.release() if self._complete.wait(timeout=timeout) is True: value = self._value return value
def terminate(self): """Terminate task. If this method called by a thread (and not a task), there is a chance that task being terminated is currently running and can interfere with GenratorExit exception that will be thrown to task. Can also be used on remotely running tasks. """ if self._location: request = _NetRequest('terminate_task', kwargs={'task': self._id, 'name': self._name}, dst=self._location, timeout=MsgTimeout) if _Peer.send_req(request) != 0: logger.warning('remote task at %s may not be valid', self._location) return -1 return 0 else: return self._scheduler._terminate_task(self)
def monitor(self, observe): """Must be used with 'yield' as 'yield task.monitor(observe)', where 'observe' is a task which will be monitored by 'task'. When 'observe' is finished (raises StopIteration or terminated due to uncaught exception), that exception is sent as a message to 'task' (monitor task). Monitor can inspect the exception and restart observed task if necessary. 'observe' can be a remote task. Can also be used on remotely running 'observe' task. """ if observe._location: # remote task request = _NetRequest('monitor', kwargs={'monitor': self, 'name': observe._name, 'task': observe._id}, dst=observe._location, timeout=MsgTimeout) reply = yield _Peer._sync_reply(request) else: reply = self._scheduler._monitor(self, observe) raise StopIteration(reply)
def del_file(self, location, file, dir=None, timeout=None): """Must be used with 'yield' as 'loc = yield scheduler.del_file(location, "file1")'. Delete 'file' from peer at 'location'. 'dir' must be same as that used for 'send_file'. """ if isinstance(dir, str) and dir: dir = dir.strip() # reject absolute path for dir if os.path.join(os.sep, dir) == dir: raise StopIteration(-1) kwargs = {'file': os.path.basename(file), 'dir': dir} req = _NetRequest('del_file', kwargs=kwargs, dst=location, timeout=timeout) reply = yield _Peer._sync_reply(req) if reply is None: reply = -1 raise StopIteration(reply)
def acquire(self, blocking=True, timeout=-1): """Must be used with 'yield' as 'yield lock.acquire()'. """ if not blocking and self._owner is not None: raise StopIteration(False) if not self._scheduler: self._scheduler = Pycos.scheduler() task = Pycos.cur_task(self._scheduler) if timeout < 0: timeout = None while self._owner is not None: if timeout is not None: if timeout <= 0: raise StopIteration(False) start = _time() self._waitlist.append(task) if (yield task._await_(timeout)) is None: try: self._waitlist.remove(task) except ValueError: pass if timeout is not None: timeout -= (_time() - start) self._owner = task raise StopIteration(True)
def finish(self, timeout=None): """Get last value 'yield'ed / value of StopIteration of task. Must be used in a task with 'yield' as 'value = yield other_task.finish()' Once task stops (finishes) executing, the last value is returned. """ value = None if self._complete is None: self._complete = Event() if (yield self._complete.wait(timeout=timeout)) is True: value = self._value elif self._complete == 0: value = self._value elif isinstance(self._complete, Event): if (yield self._complete.wait(timeout=timeout)) is True: value = self._value else: raise RuntimeError('invalid wait on %s/%s: %s' % (self._name, self._id, type(self._complete))) raise StopIteration(value)
def _receiveWithTimeout(self, count): chunk = str() while len(chunk) < count: try: tmp = self.socket.recv(count - len(chunk)) except socket.timeout: if not self._running: print("CLIENT: Socket timed out and termination requested.") return None else: continue except socket.error as e: if e[0] == errno.ECONNRESET: print("CLIENT: Connection reset by peer.") return None else: raise e if not tmp or len(tmp) == 0: print("CLIENT: Socket has been closed.") return None chunk = chunk + tmp return chunk
def _receiveWithTimeout(self, count): chunk = str() while len(chunk) < count: try: tmp = self.socket.recv(count - len(chunk)) except socket.timeout: if not self._running: print "CLIENT: Socket timed out and termination requested." return None else: continue except socket.error, e: if e[0] == errno.ECONNRESET: print "CLIENT: Connection reset by peer." return None else: raise e if not tmp or len(tmp) == 0: print "CLIENT: Socket has been closed." return None chunk = chunk + tmp return chunk
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 SocketError(str(e)) 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
def recv_into(self, *args, **kwargs): try: return self.connection.recv_into(*args, **kwargs) except OpenSSL.SSL.SysCallError as e: if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'): return 0 else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return 0 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_into(*args, **kwargs)
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)
def __init__(self, socket): self.socket = socket self.context = None self._makefile_refs = 0 self._closed = False self._exception = None self._keychain = None self._keychain_dir = None self._client_cert_chain = None # We save off the previously-configured timeout and then set it to # zero. This is done because we use select and friends to handle the # timeouts, but if we leave the timeout set on the lower socket then # Python will "kindly" call select on that socket again for us. Avoid # that by forcing the timeout to zero. self._timeout = self.socket.gettimeout() self.socket.settimeout(0)
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 SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return b'' else: raise except OpenSSL.SSL.WantReadError: rd = util.wait_for_read(self.socket, self.socket.gettimeout()) if not rd: raise timeout('The read operation timed out') else: return self.recv(*args, **kwargs) else: return data
def recv_into(self, *args, **kwargs): try: return self.connection.recv_into(*args, **kwargs) except OpenSSL.SSL.SysCallError as e: if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'): return 0 else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return 0 else: raise except OpenSSL.SSL.WantReadError: rd = util.wait_for_read(self.socket, self.socket.gettimeout()) if not rd: raise timeout('The read operation timed out') else: return self.recv_into(*args, **kwargs)
def send_packed_command(self, command): "Send an already packed command to the Redis server" if not self._sock: self.connect() try: if isinstance(command, str): command = [command] for item in command: self._sock.sendall(item) except socket.timeout: self.disconnect() raise TimeoutError("Timeout writing to socket") except socket.error: e = sys.exc_info()[1] self.disconnect() if len(e.args) == 1: errno, errmsg = 'UNKNOWN', e.args[0] else: errno = e.args[0] errmsg = e.args[1] raise ConnectionError("Error %s while writing to socket. %s." % (errno, errmsg)) except: self.disconnect() raise
def TestSite(url): protocheck(url) print "Trying: " + url try: urllib2.urlopen(url, timeout=3) except urllib2.HTTPError, e: if e.code == 405: print url + " found!" print "Now the brute force will begin! >:)" if e.code == 404: printout(str(e), YELLOW) print " - XMLRPC has been moved, removed, or blocked" sys.exit() except urllib2.URLError, g: printout("Could not identify XMLRPC. Please verify the domain.\n", YELLOW) sys.exit() except socket.timeout as e: print type(e) printout("The socket timed out, try it again.", YELLOW) sys.exit()
def connect_and_login(self): """ Establish a Telnet connection and perform a login """ self.session = Telnet() try: self.session.open(self.host, self.port, self.response_timeout) except socket.timeout: return False if not self.login(self.username, self.password): return False try: self.execute_command_lowlevel("terminal length 0") self.execute_command_lowlevel("terminal width 0") except EOFError: return False return True