Python socket.socket() Examples

The following are 50 code examples for showing how to use socket.socket(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: pycos   Author: pgiri   File: chat_server.py    (license) View Source Project 8 votes vote down vote up
def chat(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)
    print('server at %s' % str(sock.getsockname()))

    clients = set()

    try:
        while True:
            conn, addr = yield sock.accept()
            clients.add(conn)
            pycos.Task(client_send, clients, conn)
    except:
        for client in clients:
            client.shutdown(socket.SHUT_RDWR)
            client.close()
        raise 
Example 2
Project: Starfish   Author: BillWang139967   File: syscmd.py    (GNU General Public License v3.0) View Source Project 8 votes vote down vote up
def get_iphostname():
    '''??linux?????????IP??'''
    def get_ip(ifname):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
        ipaddr = socket.inet_ntoa(fcntl.ioctl(
                            sock.fileno(), 
                            0x8915,  # SIOCGIFADDR 
                            struct.pack('256s', ifname[:15]) 
                            )[20:24]
                            )   
        sock.close()
        return ipaddr
    try:
        ip = get_ip('eth0')
    except IOError:
        ip = get_ip('eno1')
    hostname = socket.gethostname()
    return {'hostname': hostname, 'ip':ip} 
Example 3
Project: pycos   Author: pgiri   File: socket_afile.py    (license) View Source Project 6 votes vote down vote up
def client_proc(host, port, input, task=None):
    # client reads input file and sends data in chunks
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock = pycos.AsyncSocket(sock)
    yield sock.connect((host, port))
    # data can be written to this asynchronous socket; however, for
    # illustration, convert its file descriptor to asynchronous file
    # and write to that instead
    afd = pycos.asyncfile.AsyncFile(sock)
    input = open(input)
    csum = hashlib.sha1()
    while True:
        data = os.read(input.fileno(), 16*1024)
        if not data:
            break
        csum.update(data)
        n = yield afd.write(data, full=True)
    afd.close()
    print('client sha1 csum: %s' % csum.hexdigest()) 
Example 4
Project: pycos   Author: pgiri   File: socket_afile.py    (license) View Source Project 6 votes vote down vote up
def server_proc(conn, task=None):
    # conn is a synchronous socket (as it is obtained from synchronous
    # 'accept'); it's file-descriptor is converted to asynchronous
    # file to read data from that
    afd = pycos.asyncfile.AsyncFile(conn)
    csum = hashlib.sha1()
    nlines = 0
    while True:
        # read lines from data
        line = yield afd.readline()
        if not line:
            break
        csum.update(line)
        nlines += 1
    afd.close()
    print('server sha1 csum: %s' % (csum.hexdigest()))
    print('lines: %s' % (nlines)) 
Example 5
Project: pycos   Author: pgiri   File: chat_server.py    (license) View Source Project 6 votes vote down vote up
def chat(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)
    print('server at %s' % str(sock.getsockname()))

    clients = set()

    try:
        while True:
            conn, addr = yield sock.accept()
            clients.add(conn)
            pycos.Task(client_send, clients, conn)
    except:
        for client in clients:
            client.shutdown(socket.SHUT_RDWR)
            client.close()
        raise 
Example 6
Project: pycos   Author: pgiri   File: sock_client.py    (license) View Source Project 6 votes vote down vote up
def client(host, port, n, task=None):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock = pycos.AsyncSocket(sock)
    yield sock.connect((host, port))
    print('%s connected' % n)
    # send arbitrary length of data
    msg = '%d: ' % n + '-' * random.randint(100,300) + '/'
    msg = msg.encode()
    yield sock.sendall(msg)
    sock.close()

# pycos.logger.setLevel(pycos.Logger.DEBUG)
# run 10 client tasks 
Example 7
Project: pycos   Author: pgiri   File: socket_afile.py    (license) View Source Project 6 votes vote down vote up
def client_proc(host, port, input, task=None):
    # client reads input file and sends data in chunks
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock = pycos.AsyncSocket(sock)
    yield sock.connect((host, port))
    # data can be written to this asynchronous socket; however, for
    # illustration, convert its file descriptor to asynchronous file
    # and write to that instead
    afd = pycos.asyncfile.AsyncFile(sock)
    input = open(input)
    csum = hashlib.sha1()
    while True:
        data = os.read(input.fileno(), 16*1024)
        if not data:
            break
        csum.update(data)
        n = yield afd.write(data, full=True)
    afd.close()
    print('client sha1 csum: %s' % csum.hexdigest()) 
Example 8
Project: pycos   Author: pgiri   File: socket_afile.py    (license) View Source Project 6 votes vote down vote up
def server_proc(conn, task=None):
    # conn is a synchronous socket (as it is obtained from synchronous
    # 'accept'); it's file-descriptor is converted to asynchronous
    # file to read data from that
    afd = pycos.asyncfile.AsyncFile(conn)
    csum = hashlib.sha1()
    nlines = 0
    while True:
        # read lines from data
        line = yield afd.readline()
        if not line:
            break
        csum.update(line)
        nlines += 1
    afd.close()
    print('server sha1 csum: %s' % (csum.hexdigest()))
    print('lines: %s' % (nlines)) 
Example 9
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _async_send(self, *args):
        """Internal use only; use 'send' with 'yield' instead.

        Asynchronous version of socket send method.
        """
        def _send():
            try:
                sent = self._rsock.send(*args)
            except:
                self._write_fn = None
                self._notifier.clear(self, _AsyncPoller._Write)
                self._write_task.throw(*sys.exc_info())
            else:
                self._write_fn = None
                self._notifier.clear(self, _AsyncPoller._Write)
                self._write_task._proceed_(sent)

        if not self._scheduler:
            self._scheduler = Pycos.scheduler()
            self._notifier = self._scheduler._notifier
            self._register()
        self._write_task = Pycos.cur_task(self._scheduler)
        self._write_task._await_()
        self._write_fn = _send
        self._notifier.add(self, _AsyncPoller._Write) 
Example 10
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _async_sendto(self, *args):
        """Internal use only; use 'sendto' with 'yield' instead.

        Asynchronous version of socket sendto method.
        """
        def _sendto():
            try:
                sent = self._rsock.sendto(*args)
            except:
                self._write_fn = None
                self._notifier.clear(self, _AsyncPoller._Write)
                self._write_task.throw(*sys.exc_info())
            else:
                self._write_fn = None
                self._notifier.clear(self, _AsyncPoller._Write)
                self._write_task._proceed_(sent)

        if not self._scheduler:
            self._scheduler = Pycos.scheduler()
            self._notifier = self._scheduler._notifier
            self._register()
        self._write_task = Pycos.cur_task(self._scheduler)
        self._write_task._await_()
        self._write_fn = _sendto
        self._notifier.add(self, _AsyncPoller._Write) 
Example 11
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _socketpair():
                if hasattr(socket, 'socketpair'):
                    return socket.socketpair()
                srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                srv_sock.bind(('127.0.0.1', 0))
                srv_sock.listen(1)
                write_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                try:
                    write_sock.setblocking(False)
                    try:
                        write_sock.connect(srv_sock.getsockname()[:2])
                    except socket.error as e:
                        if e.args[0] in (EINPROGRESS, EWOULDBLOCK):
                            pass
                        else:
                            raise
                    write_sock.setblocking(True)
                    read_sock = srv_sock.accept()[0]
                except:
                    write_sock.close()
                    raise
                finally:
                    srv_sock.close()
                return (read_sock, write_sock) 
Example 12
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _timed_out(self):
                if self._rsock and self._rsock.type & socket.SOCK_STREAM:
                    if self._read_overlap or self._write_overlap:
                        win32file.CancelIo(self._fileno)
                if self._read_task:
                    if self._rsock and self._rsock.type & socket.SOCK_DGRAM:
                        self._notifier.clear(self, _AsyncPoller._Read)
                        self._read_fn = None
                    self._read_task.throw(socket.timeout('timed out'))
                    self._read_result = self._read_task = None
                if self._write_task:
                    if self._rsock and self._rsock.type & socket.SOCK_DGRAM:
                        self._notifier.clear(self, _AsyncPoller._Write)
                        self._write_fn = None
                    self._write_task.throw(socket.timeout('timed out'))
                    self._write_result = self._write_task = None 
Example 13
Project: pycos   Author: pgiri   File: chat_server.py    (license) View Source Project 6 votes vote down vote up
def chat(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)
    print('server at %s' % str(sock.getsockname()))

    clients = set()

    try:
        while True:
            conn, addr = yield sock.accept()
            clients.add(conn)
            pycos.Task(client_send, clients, conn)
    except:
        for client in clients:
            client.shutdown(socket.SHUT_RDWR)
            client.close()
        raise 
Example 14
Project: pycos   Author: pgiri   File: socket_afile.py    (license) View Source Project 6 votes vote down vote up
def server_proc(conn, task=None):
    # conn is a synchronous socket (as it is obtained from synchronous
    # 'accept'); it's file-descriptor is converted to asynchronous
    # file to read data from that
    afd = pycos.asyncfile.AsyncFile(conn)
    csum = hashlib.sha1()
    nlines = 0
    while True:
        # read lines from data
        line = yield afd.readline()
        if not line:
            break
        csum.update(line)
        nlines += 1
    afd.close()
    print('server sha1 csum: %s' % (csum.hexdigest()))
    print('lines: %s' % (nlines)) 
Example 15
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _async_recvfrom(self, *args):
        """Internal use only; use 'recvfrom' with 'yield' instead.

        Asynchronous version of socket recvfrom method.
        """
        def _recvfrom():
            try:
                buf = self._rsock.recvfrom(*args)
            except:
                self._read_fn = None
                self._notifier.clear(self, _AsyncPoller._Read)
                self._read_task.throw(*sys.exc_info())
            else:
                self._read_fn = None
                self._notifier.clear(self, _AsyncPoller._Read)
                self._read_task._proceed_(buf)

        if not self._scheduler:
            self._scheduler = Pycos.scheduler()
            self._notifier = self._scheduler._notifier
            self._register()
        self._read_task = Pycos.cur_task(self._scheduler)
        self._read_task._await_()
        self._read_fn = _recvfrom
        self._notifier.add(self, _AsyncPoller._Read) 
Example 16
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _async_send(self, *args):
        """Internal use only; use 'send' with 'yield' instead.

        Asynchronous version of socket send method.
        """
        def _send():
            try:
                sent = self._rsock.send(*args)
            except:
                self._write_fn = None
                self._notifier.clear(self, _AsyncPoller._Write)
                self._write_task.throw(*sys.exc_info())
            else:
                self._write_fn = None
                self._notifier.clear(self, _AsyncPoller._Write)
                self._write_task._proceed_(sent)

        if not self._scheduler:
            self._scheduler = Pycos.scheduler()
            self._notifier = self._scheduler._notifier
            self._register()
        self._write_task = Pycos.cur_task(self._scheduler)
        self._write_task._await_()
        self._write_fn = _send
        self._notifier.add(self, _AsyncPoller._Write) 
Example 17
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _timed_out(self):
                if self._rsock and self._rsock.type & socket.SOCK_STREAM:
                    if self._read_overlap or self._write_overlap:
                        win32file.CancelIo(self._fileno)
                if self._read_task:
                    if self._rsock and self._rsock.type & socket.SOCK_DGRAM:
                        self._notifier.clear(self, _AsyncPoller._Read)
                        self._read_fn = None
                    self._read_task.throw(socket.timeout('timed out'))
                    self._read_result = self._read_task = None
                if self._write_task:
                    if self._rsock and self._rsock.type & socket.SOCK_DGRAM:
                        self._notifier.clear(self, _AsyncPoller._Write)
                        self._write_fn = None
                    self._write_task.throw(socket.timeout('timed out'))
                    self._write_result = self._write_task = None 
Example 18
Project: gluster-georep-tools   Author: aravindavk   File: cli.py    (MIT License) View Source Project 6 votes vote down vote up
def is_port_enabled(hostname, port):
    """
    To check if a port is enabled or not. For example
    To check ssh port is enabled or not,
        is_port_enabled(HOSTNAME, 22)

    To see glusterd port is enabled,
        is_port_enabled(HOSTNAME, 24007)
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((hostname, port))
        enabled = True
    except socket.error:
        enabled = False

    s.close()
    return enabled 
Example 19
Project: charm-plumgrid-gateway   Author: openstack   File: rpdb.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle 
Example 20
Project: charm-plumgrid-gateway   Author: openstack   File: utils.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def port_knock_units(self, sentry_units, port=22,
                         timeout=15, expect_success=True):
        """Open a TCP socket to check for a listening sevice on each
        listed juju unit.

        :param sentry_units: list of sentry unit pointers
        :param port: TCP port number, default to 22
        :param timeout: Connect timeout, default to 15 seconds
        :expect_success: True by default, set False to invert logic
        :returns: None if successful, Failure message otherwise
        """
        for unit in sentry_units:
            host = unit.info['public-address']
            connected = self.port_knock_tcp(host, port, timeout)
            if not connected and expect_success:
                return 'Socket connect failed.'
            elif connected and not expect_success:
                return 'Socket connected unexpectedly.' 
Example 21
Project: PhonePerformanceMeasure   Author: KyleCe   File: FunctionCommon.py    (MIT License) View Source Project 6 votes vote down vote up
def get_my_ip():
    """
    Returns the actual ip of the local machine.
    This code figures out what source address would be used if some traffic
    were to be sent out to some well known address on the Internet. In this
    case, a Google DNS server is used, but the specific address does not
    matter much.  No traffic is actually sent.
    """
    try:
        csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        csock.connect(('8.8.8.8', 80))
        (addr, port) = csock.getsockname()
        csock.close()
        return addr
    except socket.error:
        return "127.0.0.1" 
Example 22
Project: HTP   Author: nklose   File: ChatServer.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def run(self):
        while True:
            try:
                text = irc.recv(2040)
                if text.find('PING') != -1:
                    irc.send('PONG ' + text.split() [1] + '\r\n')
                    connected = True
                elif text.find('PRIVMSG') != -1:
                    end = text.find('!')
                    username = text[1:end]
                    start = text.find(channel + ' :')
                    message = text[start + len(channel) + 2:]
                    log('recv', '<' + username + '> ' + message)
                elif text.find('PART') != -1:
                    end = text.find('!')
                    username = text[1:end]
                    log('recv', '[' + username + '] left \n')
                elif text.find('JOIN') != -1:
                    end = text.find('!')
                    username = text[1:end]
                    log('recv', '[' + username + ']' + ' joined \n')
                else:
                    print(text)
            except socket.error:
                break 
Example 23
Project: Starfish   Author: BillWang139967   File: nbNetBase.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def __init__(self):
        self.state = 'accept'
        # ????????
        self.need_read = 10
        self.need_write = 0
        # ????????
        self.have_read = 0
        self.have_write = 0
        # ???? 
        self.buff_read = ""
        self.buff_write = ""
        # socket ??
        self.sock_obj = ""
        # ?????IP 
        self.sock_addr = ""
        # ????check_fd????
        # ?????? 
        self.read_stime= None
        # ??read????????
        self.read_itime= 30 
Example 24
Project: Starfish   Author: BillWang139967   File: nbNetBase.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def accept(self, fd):
        '''accpet??epoll?????????
        ??????socket?????
        '''
        logs.dblog("accept: accept client")
        try:
            # ??fd??????????fd?
            sock_state = self.conn_state[fd]
            # ??sock??????soket?
            sock = sock_state.sock_obj
            # ??accept???????????????????conn?????socket???addr?????????
            conn, addr = sock.accept()
            # ??socket????
            conn.setblocking(0)
            # ????????socket??,???IP??
            logs.dblog("accept: find new socket client fd(%s)" % conn.fileno())
            return conn,addr[0]
        except socket.error as msg:
            # EAGIIN ???????????????????(erron???11)
            # ECONNABORTED??TCP???????????RST(erron???103)
            # ????accept ?????? retry
            if msg.errno in (11, 103):
                return "retry" 
Example 25
Project: Starfish   Author: BillWang139967   File: nbNet_simple.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def state_log(self):
        if debug:
            msg = (
                '\n current_fd:{fd} \n state:{state}'
                '\n need_read:{need_read} \n need_write:{need_write}'
                '\n have_read:{have_read}\n have_write:{have_write}'
                '\n buff_read:{buff_read} \n buff_write:{buff_write}'
            ) .format(
                fd = self.sock_obj.fileno(), state = self.state,
                need_read = self.need_read, need_write = self.need_write,
                have_read = self.need_read, have_write = self.need_write,
                buff_read = self.need_read, buff_write = self.need_write,
            )
            logger.debug(msg)

#}}}
# ????????socket
#{{{bind_socket 
Example 26
Project: Starfish   Author: BillWang139967   File: nbNet_simple.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def accept(self, fd):
        '''??????fd???fd??
        '''
        try:
            # ??fd??????????fd?
            sock_state = self.conn_state[fd]
            # ??sock??????soket?
            sock = sock_state.sock_obj
            # ??accept???????????????????conn?????socket???addr?????????
            conn, addr = sock.accept()
            # ??socket????
            conn.setblocking(0)
            # ?epoll??????socket??fd
            self.epoll_sock.register(conn.fileno(), select.EPOLLIN)
            # ???????conn???????sock
            self.setFd(conn)
            # ????fd????read epoll????????????????
            self.conn_state[conn.fileno()].state = "read"
        except socket.error as msg:
            # ECONNABORTED??TCP???????????RST
            # EAGIIN ???????????????????
            # ????accept
            if msg.args[0] in (errno.ECONNABORTED, errno.EAGAIN):
                return
            raise 
Example 27
Project: Starfish   Author: BillWang139967   File: nbNet_simple.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def process(self, fd):
        '''read????? process ????
        '''
        # ??socket
        sock_state = self.conn_state[fd]
        # ????
        response = self.logic(sock_state.buff_read)
        # ????????????????????buff_write
        sock_state.buff_write = "%010d%s" % (len(response), response)
        # ???????
        sock_state.need_write = len(sock_state.buff_write)
        # ???????
        sock_state.state = "write"
        # ??epoll??????
        self.epoll_sock.modify(fd, select.EPOLLOUT)
        # ??write??
        self.state_machine(fd) 
Example 28
Project: Starfish   Author: BillWang139967   File: nbNetBase.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def accept(self, fd):
        '''accpet??epoll?????????
        ??????socket?????
        '''
        logs.dblog("accept: accept client")
        try:
            # ??fd??????????fd?
            sock_state = self.conn_state[fd]
            # ??sock??????soket?
            sock = sock_state.sock_obj
            # ??accept???????????????????conn?????socket???addr?????????
            conn, addr = sock.accept()
            # ??socket????
            conn.setblocking(0)
            # ????????socket??,???IP??
            logs.dblog("accept: find new socket client fd(%s)" % conn.fileno())
            return conn,addr[0]
        except socket.error as msg:
            # EAGIIN ???????????????????(erron???11)
            # ECONNABORTED??TCP???????????RST(erron???103)
            # ????accept ?????? retry
            if msg.errno in (11, 103):
                return "retry" 
Example 29
Project: Starfish   Author: BillWang139967   File: nbNetBase.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def process(self, fd):
        '''??????????logic??????'''
        logs.dblog("proces: proces start")
        # ??socket
        sock_state = self.conn_state[fd]
        # ????
        response = self.logic(sock_state.buff_read)
        # ????????????????????buff_write
        sock_state.buff_write = "%010d%s" % (len(response), response)
        # ???????
        sock_state.need_write = len(sock_state.buff_write)
        # ???????
        sock_state.state = "write"
        # ??epoll??????????epoll??????epoll???????????
        # ????????
        self.epoll_sock.modify(fd, select.EPOLLOUT)
        # ???????????
        logs.dblog("***process: process end fd state change to write***")
        sock_state.state_log() 
Example 30
Project: Starfish   Author: BillWang139967   File: nbNet_simple.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def state_log(self):
        if debug:
            msg = (
                '\n current_fd:{fd} \n state:{state}'
                '\n need_read:{need_read} \n need_write:{need_write}'
                '\n have_read:{have_read}\n have_write:{have_write}'
                '\n buff_read:{buff_read} \n buff_write:{buff_write}'
            ) .format(
                fd = self.sock_obj.fileno(), state = self.state,
                need_read = self.need_read, need_write = self.need_write,
                have_read = self.need_read, have_write = self.need_write,
                buff_read = self.need_read, buff_write = self.need_write,
            )
            logger.debug(msg)

#}}}
# ????????socket
#{{{bind_socket 
Example 31
Project: Starfish   Author: BillWang139967   File: nbNet_simple.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def __init__(self, sock, logic):
        # ??????,??????socket??????????????????
        self.conn_state = {}

        # ??setFD?????socket?????????
        self.setFd(sock)
        # ??epoll??????????????????
        self.epoll_sock = select.epoll()
        # ??????epoll???????socket????????fd?????
        # ?????????epoll????? EPOLLIN ?????
        # ??????https://docs.python.org/2.7/library/select.html?highlight=epoll#select.poll.register
        self.epoll_sock.register(sock.fileno(), select.EPOLLIN)

        # ??????
        self.logic = logic
        # ?????????????
        self.sm = {
            "accept": self.accept,
            "read": self.read,
            "write": self.write,
            "process": self.process,
            "closing": self.close,
        } 
Example 32
Project: Starfish   Author: BillWang139967   File: nbNet_simple.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def accept(self, fd):
        '''??????fd???fd??
        '''
        try:
            # ??fd??????????fd?
            sock_state = self.conn_state[fd]
            # ??sock??????soket?
            sock = sock_state.sock_obj
            # ??accept???????????????????conn?????socket???addr?????????
            conn, addr = sock.accept()
            # ??socket????
            conn.setblocking(0)
            # ?epoll??????socket??fd
            self.epoll_sock.register(conn.fileno(), select.EPOLLIN)
            # ???????conn???????sock
            self.setFd(conn)
            # ????fd????read epoll????????????????
            self.conn_state[conn.fileno()].state = "read"
        except socket.error as msg:
            # ECONNABORTED??TCP???????????RST
            # EAGIIN ???????????????????
            # ????accept
            if msg.args[0] in (errno.ECONNABORTED, errno.EAGAIN):
                return
            raise 
Example 33
Project: Starfish   Author: BillWang139967   File: nbNet_simple.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def process(self, fd):
        '''read????? process ????
        '''
        # ??socket
        sock_state = self.conn_state[fd]
        # ????
        response = self.logic(sock_state.buff_read)
        # ????????????????????buff_write
        sock_state.buff_write = "%010d%s" % (len(response), response)
        # ???????
        sock_state.need_write = len(sock_state.buff_write)
        # ???????
        sock_state.state = "write"
        # ??epoll??????
        self.epoll_sock.modify(fd, select.EPOLLOUT)
        # ??write??
        self.state_machine(fd) 
Example 34
Project: Starfish   Author: BillWang139967   File: syscmd.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def get_iphostname():
    '''??linux?????????IP??'''
    def get_ip(ifname):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
        ipaddr = socket.inet_ntoa(fcntl.ioctl(
                            sock.fileno(), 
                            0x8915,  # SIOCGIFADDR 
                            struct.pack('256s', ifname[:15]) 
                            )[20:24]
                            )   
        sock.close()
        return ipaddr
    try:
        ip = get_ip('eth0')
    except IOError:
        ip = get_ip('eno1')
    hostname = socket.gethostname()
    return {'hostname': hostname, 'ip':ip} 
Example 35
Project: piksi_ros   Author: uscresl   File: piksi_driver.py    (MIT License) View Source Project 6 votes vote down vote up
def write(self, s):
        return
        """
        Write wrapper.
        Parameters
        ----------
        s : bytes
        Bytes to write
        """
        try:
            self._write_lock.acquire()
            self.handle.sendall(s)
        except socket.error, msg:
            raise IOError
        finally:
            self._write_lock.release()


#
# # Classes for reading/writing observations to serial/udp
# 
Example 36
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def setServer(self, server):
		"""Associate this Client with given server.
		The Client will send from the Server's socket.
		The Server will use this Client instance to send replies.
		"""
		if server == None:
			if hasattr(self,'server') and self.server:
				if self.server.client != self:
					raise OSCClientError("Internal inconsistency")
				self.server.client.close()
				self.server.client = None
			self.server = None
			return

		if not isinstance(server, OSCServer):
			raise ValueError("'server' argument is not a valid OSCServer object")
		
		self._setSocket(server.socket.dup())
		self.server = server

		if self.server.client != None:
			self.server.client.close()
		
		self.server.client = self 
Example 37
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def __eq__(self, other):
		"""Compare function.
		"""
		if not isinstance(other, self.__class__):
			return False

		if self.socket and other.socket:
			sockEqual = cmp(self.socket._sock, other.socket._sock)
		else:
			sockEqual = (self.socket == None and other.socket == None)

		if not sockEqual:
			return False

		if  self.server and other.server:
			return cmp(self.server, other.server)
		else:
			return self.server == None and other.server == None 
Example 38
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def setOSCTarget(self, address, prefix=None, filters=None):
		"""Add (i.e. subscribe) a new OSCTarget, or change the prefix for an existing OSCTarget.
		  the 'address' argument can be a ((host, port) tuple) : The target server address & UDP-port
		    or a 'host' (string) : The host will be looked-up 
		  - prefix (string): The OSC-address prefix prepended to the address of each OSCMessage
		  sent to this OSCTarget (optional)
		"""
		if type(address) in str:
			address = self._searchHostAddr(address)
				
		elif (type(address) == tuple):
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except:
				pass
				
			address = (host, port)
		else:
			raise TypeError("'address' argument must be a (host, port) tuple or a 'host' string")
		
		self._setTarget(address, prefix, filters) 
Example 39
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def delOSCTarget(self, address, prefix=None):
		"""Delete the specified OSCTarget from the Client's dict.
		the 'address' argument can be a ((host, port) tuple), or a hostname.
		If the 'prefix' argument is given, the Target is only deleted if the address and prefix match.
		"""
		if type(address) in str:
			address = self._searchHostAddr(address) 

		if type(address) == tuple:
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
			
			self._delTarget(address, prefix) 
Example 40
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def hasOSCTarget(self, address, prefix=None):
		"""Return True if the given OSCTarget exists in the Client's dict.
		the 'address' argument can be a ((host, port) tuple), or a hostname.
		If the 'prefix' argument is given, the return-value is only True if the address and prefix match.
		"""
		if type(address) in str:
			address = self._searchHostAddr(address) 

		if type(address) == tuple:
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
			
			if address in list(self.targets.keys()):
				if prefix == None:
					return True
				elif prefix == self.targets[address][0]:
					return True
					
		return False 
Example 41
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, server_address, client=None, return_port=0):
		"""Instantiate an OSCServer.
		  - server_address ((host, port) tuple): the local host & UDP-port
		  the server listens on
		  - client (OSCClient instance): The OSCClient used to send replies from this server.
		  If none is supplied (default) an OSCClient will be created.
		  - return_port (int): if supplied, sets the default UDP destination-port
		  for replies coming from this server.
		"""
		UDPServer.__init__(self, server_address, self.RequestHandlerClass)
		OSCAddressSpace.__init__(self)
		
		self.setReturnPort(return_port)
		self.error_prefix = ""
		self.info_prefix = "/info"
		
		self.socket.settimeout(self.socket_timeout)
		
		self.running = False
		self.client = None
		
		if client == None:
			self.client = OSCClient(server=self)
		else:
			self.setClient(client) 
Example 42
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def _transmitMsg(self, msg):
		"""Send an OSC message over a streaming socket. Raises exception if it
		should fail. If everything is transmitted properly, True is returned. If
		socket has been closed, False.
		"""
		if not isinstance(msg, OSCMessage):
			raise TypeError("'msg' argument is not an OSCMessage or OSCBundle object")

		try:
			binary = msg.getBinary()
			length = len(binary)
			# prepend length of packet before the actual message (big endian)
			len_big_endian = array.array('c', '\0' * 4)
			struct.pack_into(">L", len_big_endian, 0, length)
			len_big_endian = len_big_endian.tostring()
			if self._transmit(len_big_endian) and self._transmit(binary):
				return True
			return False			
		except socket.error as e:
			if e[0] == errno.EPIPE: # broken pipe
				return False
			raise e 
Example 43
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def _receiveWithTimeout(self, count):
		chunk = str()
		while len(chunk) < count:
			try:
				tmp = self.socket.recv(count - len(chunk))
			except socket.timeout:
				if not self._running:
					print("CLIENT: Socket timed out and termination requested.")
					return None
				else:
					continue
			except socket.error as e:
				if e[0] == errno.ECONNRESET:
					print("CLIENT: Connection reset by peer.")
					return None
				else:
					raise e
			if not tmp or len(tmp) == 0:
				print("CLIENT: Socket has been closed.")
				return None
			chunk = chunk + tmp
		return chunk 
Example 44
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def _transmitWithTimeout(self, data):
		sent = 0
		while sent < len(data):
			try:
				tmp = self.socket.send(data[sent:])
			except socket.timeout:
				if not self._running:
					print("CLIENT: Socket timed out and termination requested.")
					return False
				else:
					continue
			except socket.error as e:
				if e[0] == errno.ECONNRESET:
					print("CLIENT: Connection reset by peer.")
					return False
				else:
					raise e
			if tmp == 0:
				return False
			sent += tmp
		return True 
Example 45
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def setServer(self, server):
		"""Associate this Client with given server.
		The Client will send from the Server's socket.
		The Server will use this Client instance to send replies.
		"""
		if server == None:
			if hasattr(self,'server') and self.server:
				if self.server.client != self:
					raise OSCClientError("Internal inconsistency")
				self.server.client.close()
				self.server.client = None
			self.server = None
			return

		if not isinstance(server, OSCServer):
			raise ValueError("'server' argument is not a valid OSCServer object")
		
		self._setSocket(server.socket.dup())
		self.server = server

		if self.server.client != None:
			self.server.client.close()
		
		self.server.client = self 
Example 46
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def __eq__(self, other):
		"""Compare function.
		"""
		if not isinstance(other, self.__class__):
			return False

		if self.socket and other.socket:
			sockEqual = cmp(self.socket._sock, other.socket._sock)
		else:
			sockEqual = (self.socket == None and other.socket == None)

		if not sockEqual:
			return False

		if  self.server and other.server:
			return cmp(self.server, other.server)
		else:
			return self.server == None and other.server == None 
Example 47
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def setOSCTarget(self, address, prefix=None, filters=None):
		"""Add (i.e. subscribe) a new OSCTarget, or change the prefix for an existing OSCTarget.
		  the 'address' argument can be a ((host, port) tuple) : The target server address & UDP-port
		    or a 'host' (string) : The host will be looked-up 
		  - prefix (string): The OSC-address prefix prepended to the address of each OSCMessage
		  sent to this OSCTarget (optional)
		"""
		if type(address) in types.StringTypes:
			address = self._searchHostAddr(address)
				
		elif (type(address) == types.TupleType):
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except:
				pass
				
			address = (host, port)
		else:
			raise TypeError("'address' argument must be a (host, port) tuple or a 'host' string")
		
		self._setTarget(address, prefix, filters) 
Example 48
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def delOSCTarget(self, address, prefix=None):
		"""Delete the specified OSCTarget from the Client's dict.
		the 'address' argument can be a ((host, port) tuple), or a hostname.
		If the 'prefix' argument is given, the Target is only deleted if the address and prefix match.
		"""
		if type(address) in types.StringTypes:
			address = self._searchHostAddr(address) 

		if type(address) == types.TupleType:
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
			
			self._delTarget(address, prefix) 
Example 49
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def hasOSCTarget(self, address, prefix=None):
		"""Return True if the given OSCTarget exists in the Client's dict.
		the 'address' argument can be a ((host, port) tuple), or a hostname.
		If the 'prefix' argument is given, the return-value is only True if the address and prefix match.
		"""
		if type(address) in types.StringTypes:
			address = self._searchHostAddr(address) 

		if type(address) == types.TupleType:
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
			
			if address in self.targets.keys():
				if prefix == None:
					return True
				elif prefix == self.targets[address][0]:
					return True
					
		return False 
Example 50
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, server_address, client=None, return_port=0):
		"""Instantiate an OSCServer.
		  - server_address ((host, port) tuple): the local host & UDP-port
		  the server listens on
		  - client (OSCClient instance): The OSCClient used to send replies from this server.
		  If none is supplied (default) an OSCClient will be created.
		  - return_port (int): if supplied, sets the default UDP destination-port
		  for replies coming from this server.
		"""
		UDPServer.__init__(self, server_address, self.RequestHandlerClass)
		OSCAddressSpace.__init__(self)
		
		self.setReturnPort(return_port)
		self.error_prefix = ""
		self.info_prefix = "/info"
		
		self.socket.settimeout(self.socket_timeout)
		
		self.running = False
		self.client = None
		
		if client == None:
			self.client = OSCClient(server=self)
		else:
			self.setClient(client)