当前位置: 首页>>代码示例>>Python>>正文


Python socket.create_connection方法代码示例

本文整理汇总了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) 
开发者ID:blackberry,项目名称:ALF,代码行数:24,代码来源:SockPuppet.py

示例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 
开发者ID:jborean93,项目名称:smbprotocol,代码行数:20,代码来源:transport.py

示例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) 
开发者ID:wbond,项目名称:oscrypto,代码行数:18,代码来源:_socket_proxy.py

示例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)) 
开发者ID:latchset,项目名称:custodia,代码行数:23,代码来源:test_custodia.py

示例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 
开发者ID:jmarth,项目名称:plugin.video.kmediatorrent,代码行数:21,代码来源:socks.py

示例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 
开发者ID:zjuchenyuan,项目名称:cc98,代码行数:25,代码来源:xinling.py

示例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() 
开发者ID:MarcelloLins,项目名称:ServerlessCrawler-VancouverRealState,代码行数:23,代码来源:test_connection.py

示例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 
开发者ID:AutohomeRadar,项目名称:Windows-Agent,代码行数:19,代码来源:transfer.py

示例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 
开发者ID:vulscanteam,项目名称:vulscan,代码行数:25,代码来源:socks.py

示例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 
开发者ID:MayOneUS,项目名称:pledgeservice,代码行数:21,代码来源:ssl_support.py

示例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 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:18,代码来源:ftplib.py

示例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) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:20,代码来源:ssl.py

示例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) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:21,代码来源:test_ssl.py

示例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 
开发者ID:genotrance,项目名称:px,代码行数:19,代码来源:test.py

示例15: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import create_connection [as 别名]
def __init__(self):
        self.s = socket.create_connection((HOST, PORT)) 
开发者ID:yingnansong,项目名称:pydouyu,代码行数:4,代码来源:client.py


注:本文中的socket.create_connection方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。