本文整理汇总了Python中gevent.socket.SOCK_STREAM属性的典型用法代码示例。如果您正苦于以下问题:Python socket.SOCK_STREAM属性的具体用法?Python socket.SOCK_STREAM怎么用?Python socket.SOCK_STREAM使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类gevent.socket
的用法示例。
在下文中一共展示了socket.SOCK_STREAM属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _dnsQuery
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
def _dnsQuery(hostname, serveListr='system', tcp=False):
u'''纯粹的查询,并没有过滤之类的功能
server:
'system'
'8.8.8.8'
['8.8.8.8','8.8.4.4']
返回值
['1.1.1.1','2.2.2.2']
'''
if serveListr == 'system':
try:
res = socket.getaddrinfo(hostname, 80, 0, socket.SOCK_STREAM, socket.IPPROTO_TCP)
return [r[4][0] for r in res]
except Exception:
info = traceback.format_exc()
logging.debug(u'[DNS][_dnsQuery][socket.getaddrinfo] 解析失败,host=%s 详细信息:' % hostname)
logging.debug('%s\r\n\r\n' % info)
return []
else:
t = dnsPool.spawn(_dnspythonQuery, hostname, serveListr, tcp)
return t.get(True)
示例2: __init__
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
def __init__(self, config):
UpstreamBase.__init__(self, config)
self.socks5_hostname = config.get('host')
self.socks5_port = config.get('port')
if self.socks5_hostname is None or self.socks5_port is None:
ms = u'[配置错误] host、port 不能为空! upstream-type:%s' % self.type
raise ConfigError(ms)
class socket(SocketBase):
# TODO: 停掉一些不支持方法。
def __init__(self, family=_socket.AF_INET, type=_socket.SOCK_STREAM, proto=0, _sock=None):
if _sock is None:
_sock = socket.upstream.socket(family=family, type=type, proto=proto)
SocketBase.__init__(self, _sock)
socket.socks5_hostname = self.socks5_hostname
socket.socks5_port = self.socks5_port
socket.upstream = self.upstream
socket.display_name = self.get_display_name()
socket.name = self.get_name()
self.socket = socket
示例3: is_port_open
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
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
示例4: run
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
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))
示例5: client
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
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()
示例6: _new_socket
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
def _new_socket(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
示例7: connect
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
def connect(self, host=None, port=None, address_family=None):
"""
Method that initiates a connection to an EPP host
"""
host = host or self.host
self.sock = socket.socket(address_family or socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(self.socket_connect_timeout) # connect timeout
self.sock.connect((host, port or self.port))
local_sock_addr = self.sock.getsockname()
local_addr, local_port = local_sock_addr[:2]
self.log.debug('connected local=%s:%s remote=%s:%s',
local_addr, local_port, self.sock.getpeername()[0], port)
self.sock.settimeout(self.socket_timeout) # regular timeout
if self.ssl_enable:
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile,
ssl_version=self.ssl_version,
ciphers=self.ssl_ciphers,
server_side=False,
cert_reqs=self.cert_required,
ca_certs=self.cacerts)
self.log.debug('%s negotiated with local=%s:%s remote=%s:%s', self.sock.version(),
local_addr, local_port, self.sock.getpeername()[0], port)
if self.validate_hostname:
try:
match_hostname(self.sock.getpeercert(), host)
except CertificateError as exp:
self.log.exception("SSL hostname mismatch")
raise EppConnectionError(str(exp))
self.greeting = EppResponse.from_xml(self.read().decode('utf-8'))
示例8: __init__
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
def __init__(self,config):
u""" 初始化直连 socket 环境 """
UpstreamBase.__init__(self,config=config)
self.source_ip = config.get('source_ip','0.0.0.0')
self.source_port = config.get('source_port',0)
self.route_cache = LRUCacheDict(500, 10 * 60 * 1000)
if self.source_ip == '0.0.0.0' and self.source_port==0:
self.source_address = None
else:
self.source_address=(self.source_ip,self.source_port)
class socket(SocketBase):
def __init__(self, family=_socket.AF_INET, type=_socket.SOCK_STREAM, proto=0,_sock=None):
if _sock is None:
_sock = socket.upsocket.socket(family=family,type=type,proto=proto)
_sock.bind(self.source_address)
SocketBase.__init__(self,_sock)
socket.source_address = self.source_address
socket.upstream = self.upstream
socket.display_name = self.get_display_name()
socket.name = self.get_name()
self.socket = socket
示例9: __init__
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
def __init__(self):
ip = config("cuckoo:resultserver:ip")
port = config("cuckoo:resultserver:port")
pool_size = config("cuckoo:resultserver:pool_size")
sock = gevent.socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind((ip, port))
except (OSError, socket.error) as e:
if e.errno == errno.EADDRINUSE:
raise CuckooCriticalError(
"Cannot bind ResultServer on port %d "
"because it was in use, bailing." % port
)
elif e.errno == errno.EADDRNOTAVAIL:
raise CuckooCriticalError(
"Unable to bind ResultServer on %s:%s %s. This "
"usually happens when you start Cuckoo without "
"bringing up the virtual interface associated with "
"the ResultServer IP address. Please refer to "
"https://cuckoo.sh/docs/faq/#troubles-problem "
"for more information." % (ip, port, e)
)
else:
raise CuckooCriticalError(
"Unable to bind ResultServer on %s:%s: %s" % (ip, port, e)
)
# We allow user to specify port 0 to get a random port, report it back
# here
_, self.port = sock.getsockname()
sock.listen(128)
self.thread = threading.Thread(
target=self.create_server, args=(sock, pool_size)
)
self.thread.daemon = True
self.thread.start()
示例10: generate_socket
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
def generate_socket(room_id):
"""Generate the socket to communicate with Bilibili Danmaku Server.
:param room_id: the id of live room.
"""
global is_first
retry_time = 0
socket.setdefaulttimeout(TIME_OUT)
userid = int(100000000 * random.random())
body = ('{"roomid": ' + str(room_id) + ', "uid": ' + str(userid) +'}')
while True:
try:
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
address = get_server(room_id)
sock.connect(
(address, 788))
send_data = send_socket_data(sock, 16 + len(body), 16,
1, 7, 1, body)
except socket.error as exc:
if retry_time == MAX_RETRY:
if not is_first:
terminate()
raise RuntimeError("重试请求过多,服务中止!")
print "服务器连接失败..."
retry_time += 1
time.sleep(4)
continue
if is_first:
print "开始接收弹幕。(Ctrl + C 退出)"
is_first = False
retry_time = 0
try:
yield sock
finally:
sock.close()
示例11: __init__
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
def __init__(self):
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
示例12: main
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
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}')
示例13: _send_command
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
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'
'--------------------------------------------------------------')
示例14: _lookup_port
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
def _lookup_port(self, port, socktype):
socktypes = []
if isinstance(port, string_types):
try:
port = int(port)
except ValueError:
try:
if socktype == 0:
origport = port
try:
port = getservbyname(port, 'tcp')
socktypes.append(SOCK_STREAM)
except error:
port = getservbyname(port, 'udp')
socktypes.append(SOCK_DGRAM)
else:
try:
if port == getservbyname(origport, 'udp'):
socktypes.append(SOCK_DGRAM)
except error:
pass
elif socktype == SOCK_STREAM:
port = getservbyname(port, 'tcp')
elif socktype == SOCK_DGRAM:
port = getservbyname(port, 'udp')
else:
raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype')
except error as ex:
if 'not found' in str(ex):
raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype')
else:
raise gaierror(str(ex))
except UnicodeEncodeError:
raise error('Int or String expected')
elif port is None:
port = 0
elif isinstance(port, integer_types):
pass
else:
raise error('Int or String expected', port, type(port))
port = int(port % 65536)
if not socktypes and socktype:
socktypes.append(socktype)
return port, socktypes
示例15: _lookup_port
# 需要导入模块: from gevent import socket [as 别名]
# 或者: from gevent.socket import SOCK_STREAM [as 别名]
def _lookup_port(self, port, socktype):
# pylint:disable=too-many-branches
socktypes = []
if isinstance(port, string_types):
try:
port = int(port)
except ValueError:
try:
if socktype == 0:
origport = port
try:
port = getservbyname(port, 'tcp')
socktypes.append(SOCK_STREAM)
except error:
port = getservbyname(port, 'udp')
socktypes.append(SOCK_DGRAM)
else:
try:
if port == getservbyname(origport, 'udp'):
socktypes.append(SOCK_DGRAM)
except error:
pass
elif socktype == SOCK_STREAM:
port = getservbyname(port, 'tcp')
elif socktype == SOCK_DGRAM:
port = getservbyname(port, 'udp')
else:
raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype')
except error as ex:
if 'not found' in str(ex):
raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype')
else:
raise gaierror(str(ex))
except UnicodeEncodeError:
raise error('Int or String expected')
elif port is None:
port = 0
elif isinstance(port, integer_types):
pass
else:
raise error('Int or String expected', port, type(port))
port = int(port % 65536)
if not socktypes and socktype:
socktypes.append(socktype)
return port, socktypes