• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python socket.fileno函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中socket.fileno函数的典型用法代码示例。如果您正苦于以下问题:Python fileno函数的具体用法?Python fileno怎么用?Python fileno使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了fileno函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: loop

    def loop(self):
        
        mask = select.POLLHUP | select.POLLERR

        self.epoll.register(self.server.fileno(), select.POLLIN | mask)

        while True:
            events = self.epoll.poll(self.EVENT_TIMEOUT_SECONDS)
            for fileno, event in events:
                if fileno == self.server.fileno():
                    try:
                        socket, client_address = self.server.accept()
                        socket.setblocking(0)
                        connection = Connection(socket)
                        self.connections[socket.fileno()] = connection
                        self.epoll.register(socket.fileno(), select.POLLIN | mask)
                        connection.last_event_time = time.time()
                    except:
                        pass
                else:
                    connection = self.connections[fileno]
                    connection.last_event_time = time.time()
                    if event & select.EPOLLERR or event & select.EPOLLHUP:
                        self.drop_connection(connection)
                    if event & select.POLLIN:
                        try:
                            data = connection.socket.recv(4096)
                        except:
                            print 'sock err'
                            self.drop_connection(connection)
                            continue
                        if data and data != '':
                            connection.on_recv(data)

                            if connection.state == connection.STATE_RESPONDING:
                                self.epoll.modify(fileno, select.EPOLLOUT | mask)
                            elif connection.state == connection.STATE_DONE:
                                self.drop_connection(connection)
                                continue
                        else:
                            self.drop_connection(connection)
                            continue

                    elif event & select.EPOLLOUT:
                        connection.respond()
                        if connection.state == connection.STATE_DONE:
                            self.drop_connection(connection)
                            continue

            now = time.time()
            for conn in self.connections.values():
                if now - conn.last_event_time > self.EVENT_TIMEOUT_SECONDS:
                    self.drop_connection(conn)
开发者ID:iskandarov-egor,项目名称:myserver,代码行数:53,代码来源:epoll_worker.py


示例2: get_client_depuis_socket

    def get_client_depuis_socket(self, socket):
        """Cette méthode retourne le client connecté, en fonction du
        socket passé en paramètre. On se base sur le fileno() du socket
        pour retrouver l'ID du client et sur le dictionnaire filenos
        faisant la correspondance.

        On retourne le client trouvé.

        """
        try:
            return self.clients[self.filenos[socket.fileno()]]
        except KeyError:
            raise KeyError("Le socket n. {0} n'est pas un socket client" \
                    .format(socket.fileno()))
开发者ID:stormi,项目名称:tsunami,代码行数:14,代码来源:serveur.py


示例3: _add_connection

 def _add_connection(self, socket):
     host, port = socket.getpeername()
     self.log.debug("Adding connection from %s:%d", host, port)
     socket.setblocking(0)
     self._pending_connections[socket.fileno()] = (time.time(),
                                                   socket)
     self._poller.register(socket, self.READ_ONLY_MASK)
开发者ID:myOvirt,项目名称:vdsm,代码行数:7,代码来源:protocoldetector.py


示例4: __init__

    def __init__(self, backend, socket, peer, rules):
        self._backend = backend
        self._socket = socket
        self._socket.setblocking(0)
        self._peer = peer

        self._rbuf = ""
        self._wbuf = ""
        self._read = 0
        self._written = 0

        self._read_delimiter = "\r\n\r\n"
        self._bytes_to_read = 0
        self._rcb = self.on_headers

        self._is_alive = True

        self._rules = rules

        self._in_id = gobject.io_add_watch(socket.fileno(),
                             gobject.IO_IN | gobject.IO_PRI,
                             self.on_read)
        self._out_id = gobject.io_add_watch(self._socket.fileno(),
                             gobject.IO_OUT,
                             self.on_write)
        self._err_id = gobject.io_add_watch(self._socket.fileno(),
                             gobject.IO_ERR,
                             self.on_error)
        self._hup_id = gobject.io_add_watch(self._socket.fileno(),
                             gobject.IO_HUP,
                             self.on_hang_up)
开发者ID:dmmartins,项目名称:amsn2,代码行数:31,代码来源:tinyhttpserver.py


示例5: set_close_on_exec

def set_close_on_exec(socket):
    """Set the FD_CLOEXEC flag."""
    if os.name == 'posix' and hasattr(fcntl, 'F_SETFD'):
        fd = socket.fileno()
        flags = fcntl.fcntl(fd, fcntl.F_GETFD, 0)
        flags = flags | fcntl.FD_CLOEXEC
        fcntl.fcntl(fd, fcntl.F_SETFD, flags)
开发者ID:MarcoYuu,项目名称:dotfiles,代码行数:7,代码来源:netbeans.py


示例6: __init__

 def __init__(self, socket, cxn_map):
     self.cxn_map = cxn_map
     self.socket = socket
     self.fd = socket.fileno()
     self.cxn_map[self.fd] = self
     self.done_reading = False
     self.read_buffer = []
开发者ID:thomasballinger,项目名称:simpleproxy,代码行数:7,代码来源:asyncproxy.py


示例7: __init__

 def __init__(self, socket, server, handler):
     self.socket = socket
     self.server = server
     self.fileno = socket.fileno()
     self.pending_data = b''
     self.handler = handler
     self.requests = []
开发者ID:eirikba,项目名称:ebakup,代码行数:7,代码来源:http_server.py


示例8: broadcast

def broadcast(source_socket, message, server_socket):
    """Function to broadcast chat messages to all connected clients"""
    # Do not send the message to server socket and the client who has
    # sent the message
    for socket in SOCKET_LIST:
        if socket != server_socket and socket != source_socket:
            try:
                for user in USERS_LIST:
                    # The user for each specific socket
                    if user[1] == str(socket.fileno()):
                        SYMM_KEY = user[2]
                        CIPHER = AES.new(SYMM_KEY)
                        h_msg = BROADCAST + message
                        msg_enc = EncodeAES(CIPHER, h_msg)
                        socket.send(msg_enc)
            except:
                # broken socket connection may be, chat client pressed ctrl+c
                # for example
                # Remove user from USERS_LIST
                for index, user in enumerate(USERS_LIST):
                    if user[1] == str(source_socket.fileno()):
                        # Close connection
                        source_socket.close()
                        # Remove socket from SOCKET_LIST
                        SOCKET_LIST.remove(source_socket)
                        del USERS_LIST[index]
                        break
开发者ID:mribeirodantas,项目名称:nsuchat2,代码行数:27,代码来源:server.py


示例9: __init__

    def __init__(self, loop=None, socket=None, address=None, dns_resolver = None, max_buffer_size = None):
        super(Socket, self).__init__()
        self._loop =loop or instance()
        self._socket = socket
        self._fileno = socket.fileno() if socket else 0
        self._address = address
        self._dns_resolver = dns_resolver or DNSResolver.default()
        self._connect_handler = False
        self._connect_timeout = 5
        self._connect_timeout_handler = None
        self._read_handler = False
        self._write_handler = False
        self._max_buffer_size = max_buffer_size or self.MAX_BUFFER_SIZE
        self._rbuffers = Buffer(max_buffer_size= self._max_buffer_size)
        self._wbuffers = None
        self._state = STATE_INITIALIZED
        self._is_enable_fast_open = False
        self._is_enable_nodelay = False
        self._is_resolve = False
        self._has_drain_event = False

        if self._socket:
            self._state = STATE_STREAMING
            self._socket.setblocking(False)
            self._read_handler = self._loop.add_fd(self._socket, MODE_IN, self._read_cb)
开发者ID:snower,项目名称:sevent,代码行数:25,代码来源:tcp.py


示例10: pub_message

def pub_message(source_socket, msg, server_socket):
    for user in USERS_LIST:
        if user[1] == str(source_socket.fileno()):
            nickname = user[3]
            break
    # Do not send the message to server socket and the client who has
    # sent the message
    for socket in SOCKET_LIST:
        if socket != server_socket and socket != source_socket:
            try:
                for user in USERS_LIST:
                    # The user for each specific socket
                    if user[1] == str(socket.fileno()):
                        SYMM_KEY = user[2]
                        CIPHER = AES.new(SYMM_KEY)
                        h_msg = PUB_MESSAGE + ',' + nickname + ',' + msg
                        msg_enc = EncodeAES(CIPHER, h_msg)
                        socket.send(msg_enc)
            except:
                print 'fedeu'
                # broken socket connection may be, chat client pressed ctrl+c
                # for example
                # Remove user from USERS_LIST
                for index, user in enumerate(USERS_LIST):
                    if user[1] == str(source_socket.fileno()):
                        # Close connection
                        source_socket.close()
                        # Remove socket from SOCKET_LIST
                        SOCKET_LIST.remove(source_socket)
                        del USERS_LIST[index]
                        break
开发者ID:mribeirodantas,项目名称:nsuchat2,代码行数:31,代码来源:server.py


示例11: __init__

    def __init__(self, poller, onMessageReceived = None, onConnected = None, onDisconnected = None,
                 socket=None, timeout=10.0, sendBufferSize = 2 ** 13, recvBufferSize = 2 ** 13):

        self.sendRandKey = None
        self.recvRandKey = None
        self.encryptor = None

        self.__socket = socket
        self.__readBuffer = bytes()
        self.__writeBuffer = bytes()
        self.__lastReadTime = time.time()
        self.__timeout = timeout
        self.__poller = poller
        if socket is not None:
            self.__socket = socket
            self.__fileno = socket.fileno()
            self.__state = CONNECTION_STATE.CONNECTED
            self.__poller.subscribe(self.__fileno,
                                     self.__processConnection,
                                     POLL_EVENT_TYPE.READ | POLL_EVENT_TYPE.WRITE | POLL_EVENT_TYPE.ERROR)
        else:
            self.__state = CONNECTION_STATE.DISCONNECTED
            self.__fileno = None
            self.__socket = None

        self.__onMessageReceived = onMessageReceived
        self.__onConnected = onConnected
        self.__onDisconnected = onDisconnected
        self.__sendBufferSize = sendBufferSize
        self.__recvBufferSize = recvBufferSize
开发者ID:chadlung,项目名称:PySyncObj,代码行数:30,代码来源:tcp_connection.py


示例12: _dispatch

    def _dispatch(self):
        removals = []
        for fno, cliobj in self.clients.iteritems():
            if not cliobj.socket:
                removals.append(fno)

        for removal in removals:
            del self.clients[removal]
                
        rl, wl, _ = select.select([self.socket.fileno(), ] + self.clients.keys(),
                                   map(lambda f: f.socket.fileno(), filter(lambda f: f.has_write(), self.clients.values())),
                                   [])

        for s in rl:
            if s == self.socket.fileno():
                # New client
                socket, address = self.socket.accept()
                self.clients[socket.fileno()] = self.CONNECTION_CLASS(server=self,
                                                                      sock=socket,
                                                                      address=address)
            else:
                if not self.clients[s].handle_read():
                    del self.clients[s]
        
        for s in wl:
            if self.clients.has_key(s) and not self.clients[s].handle_write():
                del self.clients[s]
开发者ID:flosch,项目名称:pyrpc,代码行数:27,代码来源:server.py


示例13: preexec_fn

 def preexec_fn():
     fd = socket.fileno()
     os.environ['LISTEN_FDS'] = '1'
     os.environ['LISTEN_PID'] = str(os.getpid())
     if fd != 3:
         os.dup2(fd, 3)
     os.closerange(4, 100)
开发者ID:stb-tester,项目名称:stb-tester,代码行数:7,代码来源:test_stbt_control_relay.py


示例14: bind_and_listen_on_posix_socket

def bind_and_listen_on_posix_socket(socket_name, accept_callback):
    """
    :param accept_callback: Called with `PosixSocketConnection` when a new
        connection is established.
    """
    assert socket_name is None or isinstance(socket_name, six.text_type)
    assert callable(accept_callback)

    # Py2 uses 0027 and Py3 uses 0o027, but both know
    # how to create the right value from the string '0027'.
    old_umask = os.umask(int('0027', 8))

    # Bind socket.
    socket_name, socket = _bind_posix_socket(socket_name)

    _ = os.umask(old_umask)

    # Listen on socket.
    socket.listen(0)

    def _accept_cb():
        connection, client_address = socket.accept()
        # Note: We don't have to put this socket in non blocking mode.
        #       This can cause crashes when sending big packets on OS X.

        posix_connection = PosixSocketConnection(connection)

        accept_callback(posix_connection)

    get_event_loop().add_reader(socket.fileno(), _accept_cb)

    logger.info('Listening on %r.' % socket_name)
    return socket_name
开发者ID:jonathanslenders,项目名称:pymux,代码行数:33,代码来源:posix.py


示例15: on_ssl_servername

 def on_ssl_servername(self, socket, server_name, ssl_context):
     c = self.connection_map.get(socket.fileno())
     if getattr(c, 'ssl_handshake_done', False):
         c.ready = False
         c.ssl_terminated = True
         # We do not allow client initiated SSL renegotiation
         return ssl.ALERT_DESCRIPTION_NO_RENEGOTIATION
开发者ID:MarioJC,项目名称:calibre,代码行数:7,代码来源:loop.py


示例16: _read_chunk_from_socket

def _read_chunk_from_socket(socket):
    """
    (coroutine)
    Turn socket reading into coroutine.
    """
    fd = socket.fileno()
    f = Future()

    def read_callback():
        get_event_loop().remove_reader(fd)

        # Read next chunk.
        try:
            data = socket.recv(1024)
        except OSError as e:
            # On OSX, when we try to create a new window by typing "pymux
            # new-window" in a centain pane, very often we get the following
            # error: "OSError: [Errno 9] Bad file descriptor."
            # This doesn't seem very harmful, and we can just try again.
            logger.warning('Got OSError while reading data from client: %s. '
                           'Trying again.', e)
            f.set_result('')
            return

        if data:
            f.set_result(data)
        else:
            f.set_exception(BrokenPipeError)

    get_event_loop().add_reader(fd, read_callback)

    return f
开发者ID:jonathanslenders,项目名称:pymux,代码行数:32,代码来源:posix.py


示例17: unregister_connection

 def unregister_connection(self, socket):
     fd = socket.fileno()
     try:
         self.poller.unregister(fd)
         del self.connection_map[fd]
     except KeyError:
         pass
开发者ID:dim-an,项目名称:toy-clusters,代码行数:7,代码来源:messagetoy.py


示例18: serviceClientsIn

 def serviceClientsIn(self):
     data = ""
     while 1:
         ### check the readable status of each socket(has client sent anything)
         #print "server in sleep"
         #time.sleep(.1) #needed to avoid a hang btween server/client?
         
         while not self.sockets:
             pass
         #self.socketsLock.acquire()
         r,w,e = select.select(self.sockets.values(),[],[],.1)
         #self.socketsLock.release()
         #print "serviceClientsIn loop"
         if r:  #Data has been sent on the following sockets
             try:
                 self.socketsLock.acquire()
                 for socket in r:
                     data = socket.recv(self.size)
                     while data[-4:] != self.term:
                         if BotWars.VERBOSE:
                             print "server retrieving rest of unsent data"
                         data +=  socket.recv(self.size)
                     self.indivRequestsLock.acquire()
                     self.indivRequests.append((socket.fileno(),data[:-4]))
                     if BotWars.VERBOSE:
                         #print "Server Recieve: " +pickle.loads(data[:-1])[0]
                         pass
                     self.indivRequestsLock.release()
                     self.ismore.set()
                 self.socketsLock.release()
             except error, ae:
                 self.handleError(socket)
开发者ID:lovi9573,项目名称:BotWars,代码行数:32,代码来源:tcp.py


示例19: _is_readable

def _is_readable(socket):
    """Return True if there is data to be read on the socket."""

    timeout = 0
    (rlist, wlist, elist) = select.select(
        [socket.fileno()], [], [], timeout)
    
    return bool(rlist)
开发者ID:EasonSun,项目名称:mido,代码行数:8,代码来源:sockets.py


示例20: __init__

	def __init__(self, socket, address):
		print 'connect from', address
		self.socket = socket
		self.address = address
		self.fd = socket.fileno()
		self.rbuf = ''
		self.xbuf = ''
		self.watch = {}
开发者ID:CA-IRIS,项目名称:ca-sonar,代码行数:8,代码来源:server.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python socket.fromfd函数代码示例发布时间:2022-05-27
下一篇:
Python socket.f函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap