Python gevent.socket.socket() Examples
The following are 30
code examples of gevent.socket.socket().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
gevent.socket
, or try the search function
.
Example #1
Source File: common.py From BBScan with Apache License 2.0 | 6 votes |
def is_port_open(host, port): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(3.0) if s.connect_ex((host, int(port))) == 0: return True else: return False except Exception as e: return False finally: try: s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0)) s.close() except Exception as e: pass
Example #2
Source File: gipt.py From gipt with MIT License | 6 votes |
def run(self): try: proxySock = socket.socket() self.sock.settimeout(self.config['socketTimeout']) host = self.hosts[random.randint(0, len(self.hosts) - 1)] self.proxySelector().connect(proxySock, (host[0], host[1])) pipe = Pipe(self.config) pipe.setSockPair(proxySock, self.sock) pipe.start() self.setSockPair(self.sock, proxySock) self.pipeData() except Exception: self.config['logger'].exception('Exception in Tunnel:') finally: self.sock.close() proxySock.close()
Example #3
Source File: gipt.py From gipt with MIT License | 6 votes |
def run(self): while True: for socksProxy in self.config['socksProxies']: s = socket.socket() s.settimeout(self.config['checkTimeout']) try: socksProxy.connect(s, ('www.google.com', 80)) s.send(bytearray(b'GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n')) data = s.recv(65536) if data == b'' or data == '' or data == None: raise Exception() socksProxy.fail = False self.config['logger'].debug('Proxy %s is alive.', (socksProxy.host, socksProxy.port)) except Exception: socksProxy.failCount += 1 socksProxy.fail = True self.config['logger'].debug('Proxy %s is dead.', (socksProxy.host, socksProxy.port)) finally: s.close() time.sleep(self.config['checkInterval'])
Example #4
Source File: client.py From AIT-Core with MIT License | 6 votes |
def __init__(self, zmq_context, zmq_proxy_xsub_url=ait.SERVER_DEFAULT_XSUB_URL, zmq_proxy_xpub_url=ait.SERVER_DEFAULT_XPUB_URL, **kwargs): if 'input' in kwargs and type(kwargs['input'][0]) is int: super(PortInputClient, self).__init__(zmq_context, zmq_proxy_xsub_url, zmq_proxy_xpub_url, listener=int(kwargs['input'][0])) else: raise(ValueError('Input must be port in order to create PortInputClient')) # open sub socket self.sub = gevent.socket.socket(gevent.socket.AF_INET, gevent.socket.SOCK_DGRAM)
Example #5
Source File: server.py From PhonePi_SampleServer with MIT License | 6 votes |
def _udp_socket(address, backlog=50, reuse_addr=None, family=_socket.AF_INET): # backlog argument for compat with tcp_listener # pylint:disable=unused-argument # we want gevent.socket.socket here sock = socket(family=family, type=_socket.SOCK_DGRAM) if reuse_addr is not None: sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, reuse_addr) try: sock.bind(address) except _socket.error as ex: strerror = getattr(ex, 'strerror', None) if strerror is not None: ex.strerror = strerror + ': ' + repr(address) raise return sock
Example #6
Source File: ggevent.py From Flask-P2P with MIT License | 6 votes |
def patch(self): from gevent import monkey monkey.noisy = False # if the new version is used make sure to patch subprocess if gevent.version_info[0] == 0: monkey.patch_all() else: monkey.patch_all(subprocess=True) # monkey patch sendfile to make it none blocking patch_sendfile() # patch sockets sockets = [] for s in self.sockets: sockets.append(socket(s.FAMILY, _socket.SOCK_STREAM, _sock=s)) self.sockets = sockets
Example #7
Source File: connection.py From CSGO-Market-Float-Finder with MIT License | 6 votes |
def cleanup(self): super(TCPConnection, self).cleanup() self.write_buffer = [] self.read_buffer = '' if self.socket: self.socket.close() self.socket = None if self.net_read: self.net_read.kill() self.net_read = None if self.net_write: self.net_write.kill() self.net_write = None if not self.connected: return self.client.handle_disconnected(self.user_abort)
Example #8
Source File: precomputed.py From cloud-volume with BSD 3-Clause "New" or "Revised" License | 6 votes |
def green_threads(self, val): if val and socket.socket is not gevent.socket.socket: warn(""" WARNING: green_threads is set but this process is not monkey patched. This will cause severely degraded performance. CloudVolume uses gevent for cooperative (green) threading but it requires patching the Python standard library to perform asynchronous IO. Add this code to the top of your program (before any other imports): import gevent.monkey gevent.monkey.patch_all(threads=False) More Information: http://www.gevent.org/intro.html#monkey-patching """) self.config.green = bool(val)
Example #9
Source File: connection.py From steam with MIT License | 6 votes |
def connect(self, server_addr): self._new_socket() logger.debug("Attempting connection to %s", str(server_addr)) try: self._connect(server_addr) except socket.error: return False self.server_addr = server_addr self.recv_queue.queue.clear() self._reader = gevent.spawn(self._reader_loop) self._writer = gevent.spawn(self._writer_loop) logger.debug("Connected.") self.event_connected.set() return True
Example #10
Source File: connectionhandler.py From taserver with GNU Affero General Public License v3.0 | 6 votes |
def run(self): gevent.getcurrent().name = self.task_name while True: msg = self.outgoing_queue.get() if not isinstance(msg, PeerDisconnectedMessage): try: msg_bytes = self.encode(msg) self.send(msg_bytes) except (ConnectionResetError, ConnectionAbortedError): # Ignore a closed connection here. The reader will notice # it and send us the DisconnectedMessage to tell us that # we can close the socket and terminate pass else: self.sock.close() if msg.exception: raise msg.exception else: break self.logger.info('%s(%s): writer exiting gracefully' % (self.task_name, self.task_id))
Example #11
Source File: server.py From PhonePi_SampleServer with MIT License | 6 votes |
def __init__(self, listener, handle=None, backlog=None, spawn='default', **ssl_args): BaseServer.__init__(self, listener, handle=handle, spawn=spawn) try: if ssl_args: ssl_args.setdefault('server_side', True) if 'ssl_context' in ssl_args: ssl_context = ssl_args.pop('ssl_context') self.wrap_socket = ssl_context.wrap_socket self.ssl_args = ssl_args else: from gevent.ssl import wrap_socket self.wrap_socket = wrap_socket self.ssl_args = ssl_args else: self.ssl_args = None if backlog is not None: if hasattr(self, 'socket'): raise TypeError('backlog must be None when a socket instance is passed') self.backlog = backlog except: self.close() raise
Example #12
Source File: connectionhandler.py From taserver with GNU Affero General Public License v3.0 | 6 votes |
def run(self, retry_time = None): task_id = id(gevent.getcurrent()) try: while True: try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect((self.address, self.port)) self._handle(sock, (str(self.address), self.port)) break except (ConnectionRefusedError, TimeoutError) as e: if retry_time is not None: if isinstance(e, ConnectionRefusedError): reason = 'remote end is refusing connections' else: reason = 'connection timed out' self.logger.info('%s(%s): %s. Reconnecting in %d seconds...' % (self.task_name, task_id, reason, retry_time)) gevent.sleep(retry_time) else: break except Exception: self.logger.exception('%s(%s) terminated with an exception' % (self.task_name, task_id))
Example #13
Source File: ggevent.py From jbox with MIT License | 6 votes |
def patch(self): from gevent import monkey monkey.noisy = False # if the new version is used make sure to patch subprocess if gevent.version_info[0] == 0: monkey.patch_all() else: monkey.patch_all(subprocess=True) # monkey patch sendfile to make it none blocking patch_sendfile() # patch sockets sockets = [] for s in self.sockets: if sys.version_info[0] == 3: sockets.append(socket(s.FAMILY, _socket.SOCK_STREAM, fileno=s.sock.fileno())) else: sockets.append(socket(s.FAMILY, _socket.SOCK_STREAM, _sock=s)) self.sockets = sockets
Example #14
Source File: server.py From PhonePi_SampleServer with MIT License | 5 votes |
def init_socket(self): if not hasattr(self, 'socket'): # FIXME: clean up the socket lifetime # pylint:disable=attribute-defined-outside-init self.socket = self.get_listener(self.address, self.family) self.address = self.socket.getsockname() self._socket = self.socket try: self._socket = self._socket._sock except AttributeError: pass
Example #15
Source File: server.py From PhonePi_SampleServer with MIT License | 5 votes |
def do_read(self): sock = self.socket try: fd, address = sock._accept() except BlockingIOError: # python 2: pylint: disable=undefined-variable if not sock.timeout: return raise sock = socket(sock.family, sock.type, sock.proto, fileno=fd) # XXX Python issue #7995? return sock, address
Example #16
Source File: server.py From PhonePi_SampleServer with MIT License | 5 votes |
def do_read(self): try: client_socket, address = self.socket.accept() except _socket.error as err: if err.args[0] == EWOULDBLOCK: return raise sockobj = socket(_sock=client_socket) if PYPY: client_socket._drop() return sockobj, address
Example #17
Source File: server.py From PhonePi_SampleServer with MIT License | 5 votes |
def sendto(self, *args): self._writelock.acquire() try: self.socket.sendto(*args) finally: self._writelock.release()
Example #18
Source File: server.py From PhonePi_SampleServer with MIT License | 5 votes |
def _tcp_listener(address, backlog=50, reuse_addr=None, family=_socket.AF_INET): """A shortcut to create a TCP socket, bind it and put it into listening state.""" sock = socket(family=family) if reuse_addr is not None: sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, reuse_addr) try: sock.bind(address) except _socket.error as ex: strerror = getattr(ex, 'strerror', None) if strerror is not None: ex.strerror = strerror + ': ' + repr(address) raise sock.listen(backlog) sock.setblocking(0) return sock
Example #19
Source File: firewall.py From taserver with GNU Affero General Public License v3.0 | 5 votes |
def _send_command(self, command): server_address = ("127.0.0.1", self.ports['firewall']) proxy_addresses = (("127.0.0.1", self.ports['gameserver1firewall']), ("127.0.0.1", self.ports['gameserver2firewall'])) try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect(server_address) TcpMessageWriter(sock).send(json.dumps(command).encode('utf8')) if command['list'] == 'whitelist': for proxy_address in proxy_addresses: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect(proxy_address) if command['action'] == 'reset': message = b'reset' else: address = IPv4Address(command['ip']) action = b'a' if command['action'] == 'add' else b'r' message = action + struct.pack('<L', command['player_id']) + address.packed sock.sendall(struct.pack('<L', len(message))) sock.sendall(message) sock.shutdown(socket.SHUT_RDWR) except ConnectionRefusedError: logger = logging.getLogger(__name__) logger.warning('\n' '--------------------------------------------------------------\n' 'Warning: Failed to connect to taserver firewall for modifying \n' 'the firewall rules.\n' 'Did you forget to run start_taserver_firewall.py (as admin)?\n' 'If you want to run without the firewall and udpproxy you will need\n' 'to change the gameserver port to 7777 in gameserverlauncher.ini.\n' '--------------------------------------------------------------')
Example #20
Source File: gipt.py From gipt with MIT License | 5 votes |
def __init__(self, config, port, hosts, proxySelector): Concurrent.__init__(self) self.config = config self.hosts = hosts self.proxySelector = proxySelector self.sock = socket.socket() try: self.sock.bind(('0.0.0.0', port)) self.sock.listen(50) except Exception: self.config['logger'].exception('Exception in Server init:') raise
Example #21
Source File: gipt.py From gipt with MIT License | 5 votes |
def run(self): #tunnels = [] while True: try: clientSock, clientAddr = self.sock.accept() clientSock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) tunnel = Tunnel(self.config, clientSock, self.hosts, self.proxySelector) tunnel.start() self.config['logger'].debug('Accepted connection from %s.', str(clientAddr)) #tunnels.append(tunnel) except Exception: self.config['logger'].exception('Exception in Server run:')
Example #22
Source File: connection.py From CSGO-Market-Float-Finder with MIT License | 5 votes |
def _heartbeat(self, time): while self.socket: sleep(time) message = msg_base.ProtobufMessage(steammessages_clientserver_pb2.CMsgClientHeartBeat, EMsg.ClientHeartBeat) self.send_message(message)
Example #23
Source File: connection.py From CSGO-Market-Float-Finder with MIT License | 5 votes |
def __init__(self, client): super(TCPConnection, self).__init__(client) self.socket = None self.write_buffer = [] self.read_buffer = '' self.net_read = None self.net_write = None
Example #24
Source File: connection.py From CSGO-Market-Float-Finder with MIT License | 5 votes |
def connect(self, address): super(TCPConnection, self).connect(address) self.socket = socket.socket() with gevent.Timeout(5, False) as timeout: self.socket.connect(address) self.net_read = gevent.spawn(self.__read_data) self.connected = True return True return False
Example #25
Source File: connection.py From CSGO-Market-Float-Finder with MIT License | 5 votes |
def __write_data(self): while len(self.write_buffer) > 0: try: buffer = self.write_buffer[0] self.socket.sendall(buffer) except IOError as e: self.net_write = None self.cleanup() return self.write_buffer.pop(0) self.net_write = None
Example #26
Source File: monkey.py From mrq with MIT License | 5 votes |
def patch_network_latency(seconds=0.01): """ Add random latency to all I/O operations """ # Accept float(0.1), "0.1", "0.1-0.2" def sleep(): if isinstance(seconds, float): time.sleep(seconds) elif isinstance(seconds, basestring): # pylint: disable=maybe-no-member if "-" in seconds: time.sleep(random.uniform( float(seconds.split("-")[0]), float(seconds.split("-")[1]) )) else: time.sleep(float(seconds)) def _patched_method(old_method, *args, **kwargs): sleep() return old_method(*args, **kwargs) socket_methods = [ "send", "sendall", "sendto", "recv", "recvfrom", "recvfrom_into", "recv_into", "connect", "connect_ex", "close" ] from socket import socket as _socketmodule from gevent.socket import socket as _geventmodule from gevent.ssl import SSLSocket as _sslmodule # pylint: disable=no-name-in-module for method in socket_methods: patch_method(_socketmodule, method, _patched_method) patch_method(_geventmodule, method, _patched_method) patch_method(_sslmodule, method, _patched_method)
Example #27
Source File: getauthcode.py From taserver with GNU Affero General Public License v3.0 | 5 votes |
def main(args): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(server_address) writer = TcpMessageWriter(sock) reader = TcpMessageReader(sock) writer.send(Auth2LoginAuthCodeRequestMessage('getauthcode', args.username, args.email).to_bytes()) result = parse_message_from_bytes(reader.receive()) if not isinstance(result, Login2AuthAuthCodeResultMessage) or result.authcode is None: print(result.error_message) else: print(f'Received authcode {result.authcode} for username {result.login_name}')
Example #28
Source File: connectionhandler.py From taserver with GNU Affero General Public License v3.0 | 5 votes |
def receive(self): """ Receive a message from a socket and return the bytes that make up the message """ raise NotImplementedError('receive must be implemented in a subclass of ConnectionWriter')
Example #29
Source File: connectionhandler.py From taserver with GNU Affero General Public License v3.0 | 5 votes |
def send(self, msg_bytes): """ Send the bytes that make up a message out over the socket """ raise NotImplementedError('send must be implemented in a subclass of ConnectionWriter')
Example #30
Source File: serverclient.py From gipc with MIT License | 5 votes |
def client(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', PORT)) f = sock.makefile(mode='wr') f.write(MSG) f.flush() assert f.readline() == MSG f.close()