python类bind()的实例源码

tcp.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def _resolveIPv6(ip, port):
    """
    Resolve an IPv6 literal into an IPv6 address.

    This is necessary to resolve any embedded scope identifiers to the relevant
    C{sin6_scope_id} for use with C{socket.connect()}, C{socket.listen()}, or
    C{socket.bind()}; see U{RFC 3493 <https://tools.ietf.org/html/rfc3493>} for
    more information.

    @param ip: An IPv6 address literal.
    @type ip: C{str}

    @param port: A port number.
    @type port: C{int}

    @return: a 4-tuple of C{(host, port, flow, scope)}, suitable for use as an
        IPv6 address.

    @raise socket.gaierror: if either the IP or port is not numeric as it
        should be.
    """
    return socket.getaddrinfo(ip, port, 0, 0, 0, _NUMERIC_ONLY)[0][4]
modbus_tcp_bridge.py 文件源码 项目:sdk-samples 作者: cradlepoint 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def bind_server(self):
        """
        Wrap the bind process
        :return:
        """
        # define the socket resource, including the type (stream == "TCP")
        bind_address = (self.host_ip, self.host_port)
        self.logger.debug("Preparing TCP socket {}".format(bind_address))
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # try to speed up reuse
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # attempt to actually lock resource, which may fail if unavailable
        try:
            self.server.bind(bind_address)
        except OSError as msg:
            self.logger.error("socket.bind() failed - {}".format(msg))
            self.server.close()
            self.server = None
            self.logger.error("TCP server socket closed")
            raise ConnectionError

        # only allow 1 client at a time
        self.server.listen(1)
        self.logger.info("Waiting on TCP {}, protocol:{}".format(
            bind_address, self.host_protocol))

        return self.server
tcp.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __init__(self, host, port, bindAddress, connector, reactor=None):
        # BaseClient.__init__ is invoked later
        self.connector = connector
        self.addr = (host, port)

        whenDone = self.resolveAddress
        err = None
        skt = None

        if abstract.isIPAddress(host):
            self._requiresResolution = False
        elif abstract.isIPv6Address(host):
            self._requiresResolution = False
            self.addr = _resolveIPv6(host, port)
            self.addressFamily = socket.AF_INET6
            self._addressType = address.IPv6Address
        else:
            self._requiresResolution = True
        try:
            skt = self.createInternetSocket()
        except socket.error as se:
            err = error.ConnectBindError(se.args[0], se.args[1])
            whenDone = None
        if whenDone and bindAddress is not None:
            try:
                if abstract.isIPv6Address(bindAddress[0]):
                    bindinfo = _resolveIPv6(*bindAddress)
                else:
                    bindinfo = bindAddress
                skt.bind(bindinfo)
            except socket.error as se:
                err = error.ConnectBindError(se.args[0], se.args[1])
                whenDone = None
        self._finishInit(whenDone, skt, err, reactor)
tcp.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def startListening(self):
        """Create and bind my socket, and begin listening on it.

        This is called on unserialization, and must be called after creating a
        server to begin listening on the specified port.
        """
        if self._preexistingSocket is None:
            # Create a new socket and make it listen
            try:
                skt = self.createInternetSocket()
                if self.addressFamily == socket.AF_INET6:
                    addr = _resolveIPv6(self.interface, self.port)
                else:
                    addr = (self.interface, self.port)
                skt.bind(addr)
            except socket.error as le:
                raise CannotListenError(self.interface, self.port, le)
            skt.listen(self.backlog)
        else:
            # Re-use the externally specified socket
            skt = self._preexistingSocket
            self._preexistingSocket = None
            # Avoid shutting it down at the end.
            self._shouldShutdown = False

        # Make sure that if we listened on port 0, we update that to
        # reflect what the OS actually assigned us.
        self._realPortNumber = skt.getsockname()[1]

        log.msg("%s starting on %s" % (
                self._getLogPrefix(self.factory), self._realPortNumber))

        # The order of the next 5 lines is kind of bizarre.  If no one
        # can explain it, perhaps we should re-arrange them.
        self.factory.doStart()
        self.connected = True
        self.socket = skt
        self.fileno = self.socket.fileno
        self.numberAccepts = 100

        self.startReading()
server.py 文件源码 项目:LMDocker-project 作者: xiaozhazi 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def accept_file():

#   host = get_ip_address('eth1')   
    host=ni.ifaddresses('p1p1')[2][0]['addr']
    port = 10018
    socket.bind((host,port))
    socket.listen(5)

    conn, addr = socket.accept()
    print 'connecting from:', addr

    buffer = conn.recv(1024)
    global full_path
    full_path = buffer.split('\0')[0]
    print full_path

    global name
    temp = full_path.split('/',2)[2]
    name = temp.split('.',2)[0]
    print name

    if True == os.path.isfile(full_path):
        print 'file(%s) is already exist'% full_path
        del_op = 'rm '+full_path
        os.system(del_op)

    dir = full_path.split('.')[0]
    if True == os.path.exists(dir):
        print 'directory already exist'% dir
        delete_con ='docker rm -f '+name+ ' >/dev/null 2>&1'
        print delete_con
        os.system(delete_con)
        del_dir = 'rm -rf '+ dir
        os.system(del_dir)


    conn.send('ready')
    fname = open(full_path, 'wb')
    while True:
        strng = conn.recv(4096)
        if not strng:
            fname.close()
            conn.close()
            print "recv file success"
            break
        else:
            fname.write(strng)
Messager.py 文件源码 项目:RPi-distributed-ML 作者: revan 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __init__(self):
        self.loop = ioloop.IOLoop.current()
        # load topography from file
        self._loadTopology()

        self.context = zmq.Context()

        self.zk = KazooClient()
        self.zk.start(timeout=1000)

        # send own address to zookeeper
        self.zk.ensure_path("/addr")
        self.zk.create(("/addr/%s" % self.getOwnName()), bytes(self.getOwnAddr(), "UTF-8"))

        # get IP addresses from zookeeper
        all_names = {k for k in self.topo.keys() if k.isnumeric() and k != self.getOwnName()}
        self.addresses = {}
        for name in all_names:
            cv = threading.Condition()
            cv.acquire()

            def wakeup_watch(stat):
                cv.acquire()
                cv.notify()
                cv.release()

            ex = self.zk.exists(("/addr/%s" % name), wakeup_watch)
            if not ex:
                cv.wait()
            (addr, _) = self.zk.get("/addr/%s" % name)
            self.addresses[name] = addr.decode("UTF-8")

        print('All nodes checked in to Zookeeper.')

        # create PAIR connections for each network link
        self.neighbors = {}
        self._allNodes = {}
        for name in all_names:
            # lower device establishes connection to avoid duplicate
            socket = self.context.socket(zmq.PAIR)
            if int(name) > int(self.getOwnName()):
                socket.connect(self.getAddr(name))
            else:
                socket.bind('tcp://*:%d' % self._findPortFor(name))

            self._allNodes[name] = socket
            if name in self.topo[self.getOwnName()]:
                self.neighbors[name] = socket

        self.resetSyncInbox()
        self.sync_cv = threading.Condition()

        self.streams = {}


问题


面经


文章

微信
公众号

扫码关注公众号