本文整理匯總了Python中socket.create_connection方法的典型用法代碼示例。如果您正苦於以下問題:Python socket.create_connection方法的具體用法?Python socket.create_connection怎麽用?Python socket.create_connection使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類socket
的用法示例。
在下文中一共展示了socket.create_connection方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: connect
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [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)
示例2: socket_connect
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def socket_connect(func):
def wrapped(self, *args, **kwargs):
if not self._connected:
log.info("Connecting to DirectTcp socket")
try:
self._sock = socket.create_connection((self.server, self.port), timeout=self.timeout)
except (OSError, socket.gaierror) as err:
raise ValueError("Failed to connect to '%s:%s': %s" % (self.server, self.port, str(err)))
self._sock.settimeout(None) # Make sure the socket is in blocking mode.
self._t_recv = threading.Thread(target=self.recv_thread, name="recv-%s:%s" % (self.server, self.port))
self._t_recv.daemon = True
self._t_recv.start()
self._connected = True
func(self, *args, **kwargs)
return wrapped
示例3: make_socket_proxy
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def make_socket_proxy(ip, port, send_callback=None, recv_callback=None):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('', 8080))
server.listen(1)
t = threading.Thread(
target=listen,
args=(server, ip, port, send_callback, recv_callback)
)
t.start()
sock = socket.create_connection(('localhost', 8080))
sock.settimeout(1)
t.join()
with _socket_lock:
data = _sockets[t.ident]
return (sock, data['lsock'], data['rsock'], server)
示例4: check_socket
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def check_socket(self):
url = urlparse(self.socket_url)
timeout = 0.5
if url.scheme == 'http+unix':
address = unquote(url.netloc)
s = socket.socket(socket.AF_UNIX)
s.settimeout(timeout)
try:
s.connect(address)
except OSError as e:
self.fail("Server socket unavailable: {}".format(e))
finally:
s.close()
else:
host, port = url.netloc.rsplit(":", 1)
try:
socket.create_connection(
(host, int(port)), timeout=timeout
).close()
except OSError as e:
self.fail("Server socket unavailable: {}".format(e))
示例5: create_connection
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def create_connection(dest_pair, proxy_type=None, proxy_addr=None,
proxy_port=None, proxy_username=None,
proxy_password=None, timeout=None):
"""create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object
Like socket.create_connection(), but connects to proxy
before returning the socket object.
dest_pair - 2-tuple of (IP/hostname, port).
**proxy_args - Same args passed to socksocket.set_proxy().
timeout - Optional socket timeout value, in seconds.
"""
sock = socksocket()
if isinstance(timeout, (int, float)):
sock.settimeout(timeout)
sock.set_proxy(proxy_type, proxy_addr, proxy_port,
proxy_username, proxy_password)
sock.connect(dest_pair)
return sock
示例6: function_hook_parameter
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def function_hook_parameter(oldfunc, parameter_index, parameter_name, parameter_value):
"""
這個函數隻是用於輔助實現多IP爬取,並不是很重要,你可以放心地跳過此函數繼續閱讀
創造一個wrapper函數,劫持oldfunc傳入的第parameter_index名為parameter_name的函數,固定其值為parameter_value; 不影響調用該函數時傳入的任何其他參數
用法: 原函數 = function_hook_parameter(原函數, 從1開始計數的參數所處的位置, 這個參數的名稱, 需要替換成的參數值)
例子: 需要劫持socket.create_connection這個函數,其函數原型如下:
create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None)
需要對其第3個參數source_address固定為value,劫持方法如下
socket.create_connection = function_hook_parameter(socket.create_connection, 3, "source_address", value)
"""
real_func = oldfunc
def newfunc(*args, **kwargs): # args是參數列表list,kwargs是帶有名稱keyword的參數dict
newargs = list(args)
if len(args) >= parameter_index: # 如果這個參數被直接傳入,那麽肯定其前麵的參數都是無名稱的參數,args的長度肯定長於其所在的位置
newargs[parameter_index - 1] = parameter_value # 第3個參數在list的下表是2
else: # 如果不是直接傳入,那麽就在kwargs中 或者可選參數不存在這個參數,強製更新掉kwargs即可
kwargs[parameter_name] = parameter_value
return real_func(*newargs, **kwargs)
return newfunc
示例7: test_defer_connect
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def test_defer_connect(self):
import socket
for db in self.databases:
d = db.copy()
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(d['unix_socket'])
except KeyError:
sock = socket.create_connection(
(d.get('host', 'localhost'), d.get('port', 3306)))
for k in ['unix_socket', 'host', 'port']:
try:
del d[k]
except KeyError:
pass
c = pymysql.connect(defer_connect=True, **d)
self.assertFalse(c.open)
c.connect(sock)
c.close()
sock.close()
示例8: insure_conn
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def insure_conn(self):
"""
insure tcp connection is alive, if not alive or client
is None create a new tcp connection.
Args:
addr (JSONClient): client which can send rpc request
Returns:
JSONClient with given addr
"""
for _ in range(3):
try:
self.call('Transfer.Ping', None)
except Exception as e:
logging.error(e)
logging.error("lose connection to transfer, prepare to rebuild")
self.socket = socket.create_connection(self.addr)
break
示例9: create_connection
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def create_connection(dest_pair, proxy_type=None, proxy_addr=None,
proxy_port=None, proxy_rdns=True,
proxy_username=None, proxy_password=None,
timeout=None, source_address=None):
"""create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object
Like socket.create_connection(), but connects to proxy
before returning the socket object.
dest_pair - 2-tuple of (IP/hostname, port).
**proxy_args - Same args passed to socksocket.set_proxy() if present.
timeout - Optional socket timeout value, in seconds.
source_address - tuple (host, port) for the socket to bind to as its source
address before connecting (only for compatibility)
"""
sock = socksocket()
if isinstance(timeout, (int, float)):
sock.settimeout(timeout)
if proxy_type is not None:
sock.set_proxy(proxy_type, proxy_addr, proxy_port, proxy_rdns,
proxy_username, proxy_password)
sock.connect(dest_pair)
return sock
示例10: connect
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def connect(self):
sock = socket.create_connection(
(self.host, self.port), getattr(self, 'source_address', None)
)
# Handle the socket if a (proxy) tunnel is present
if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None):
self.sock = sock
self._tunnel()
self.sock = ssl.wrap_socket(
sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle
)
try:
match_hostname(self.sock.getpeercert(), self.host)
except CertificateError:
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
raise
示例11: connect
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def connect(self, host='', port=0, timeout=-999):
'''Connect to host. Arguments are:
- host: hostname to connect to (string, default previous host)
- port: port to connect to (integer, default previous port)
'''
if host != '':
self.host = host
if port > 0:
self.port = port
if timeout != -999:
self.timeout = timeout
self.sock = socket.create_connection((self.host, self.port), self.timeout)
self.af = self.sock.family
self.file = self.sock.makefile('rb')
self.welcome = self.getresp()
return self.welcome
示例12: get_server_certificate
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
"""Retrieve the certificate from the server at the specified address,
and return it as a PEM-encoded string.
If 'ca_certs' is specified, validate the server cert against it.
If 'ssl_version' is specified, use it in the connection attempt."""
host, port = addr
if ca_certs is not None:
cert_reqs = CERT_REQUIRED
else:
cert_reqs = CERT_NONE
context = _create_stdlib_context(ssl_version,
cert_reqs=cert_reqs,
cafile=ca_certs)
with closing(create_connection(addr)) as sock:
with closing(context.wrap_socket(sock)) as sslsock:
dercert = sslsock.getpeercert(True)
return DER_cert_to_PEM_cert(dercert)
示例13: test_recv_zero
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def test_recv_zero(self):
server = ThreadedEchoServer(CERTFILE)
server.__enter__()
self.addCleanup(server.__exit__, None, None)
s = socket.create_connection((HOST, server.port))
self.addCleanup(s.close)
s = ssl.wrap_socket(s, suppress_ragged_eofs=False)
self.addCleanup(s.close)
# recv/read(0) should return no data
s.send(b"data")
self.assertEqual(s.recv(0), b"")
self.assertEqual(s.read(0), b"")
self.assertEqual(s.read(), b"data")
# Should not block if the other end sends no data
s.setblocking(False)
self.assertEqual(s.recv(0), b"")
self.assertEqual(s.recv_into(bytearray()), 0)
示例14: checkPxStart
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def checkPxStart(ip, port):
# Make sure Px starts
retry = 20
while True:
try:
socket.create_connection((ip, port), 2)
break
except (socket.timeout, ConnectionRefusedError):
time.sleep(1)
retry -= 1
if retry == 0:
print("Px didn't start @ %s:%d" % (ip, port))
return False
return True
# Test --listen and --port, --hostonly, --gateway and --allow
示例15: __init__
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import create_connection [as 別名]
def __init__(self):
self.s = socket.create_connection((HOST, PORT))