Python socket.socket() Examples

The following are code examples for showing how to use socket.socket(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: fs_image   Author: facebookincubator   File: yum_dnf_from_snapshot.py    MIT License 7 votes vote down vote up
def _repo_server(
    repo_server_bin: Path,
    sock: socket.socket,
    storage_cfg: str,
    snapshot_dir: Path
):
    '''
    Invokes `repo-server` with the given storage & snapshot; passes it
    ownership of the bound TCP socket -- it listens & accepts connections.
    '''
    # This could be a thread, but it's probably not worth the risks
    # involved in mixing threads & subprocess (yes, lots of programs do,
    # but yes, far fewer do it safely).
    with sock, subprocess.Popen([
        repo_server_bin,
        '--socket-fd', str(sock.fileno()),
        '--storage', storage_cfg,
        '--snapshot-dir', snapshot_dir,
    ], pass_fds=[sock.fileno()]) as server_proc:
        try:
            yield server_proc
        finally:
            server_proc.kill()  # It's a read-only proxy, abort ASAP 
Example 2
Project: pyblish-win   Author: pyblish   File: asyncore.py    GNU Lesser General Public License v3.0 7 votes vote down vote up
def set_reuse_addr(self):
        # try to re-use a server port if possible
        try:
            self.socket.setsockopt(
                socket.SOL_SOCKET, socket.SO_REUSEADDR,
                self.socket.getsockopt(socket.SOL_SOCKET,
                                       socket.SO_REUSEADDR) | 1
                )
        except socket.error:
            pass

    # ==================================================
    # predicates for select()
    # these are used as filters for the lists of sockets
    # to pass to select().
    # ================================================== 
Example 3
Project: flexnet   Author: ressy   File: client.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, server, port=None):
        if port is None:
            port, server = server.split('@')
            port = int(port)

        self.server   = server # server hostname for TCP connections
        self.port     = port   # server port number for TCP connections
        self.debug    = False  # show raw binary sent and received
        self.verbose  = False  # show parsed messages received
        self.oldproto = None   # will be set later if server version < VER_NEW

        self.user    = os.environ.get('USER') or ''
        self.host    = socket.gethostname()
        self.vendor  = "" # empty to start, then vendor name
        self.tty     = '/dev/pts/1'
        self.pid     = str(os.getpid())
        self.arch    = 'x64_lsb' # OS/arch ("64-bit Linux Standard Base"?)
        self.version = (11,11) # "this" lmstat version

        self.connect()

    # Lower-level public methods for specific connection and request types 
Example 4
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, host, port):
        """
        Initializes the handler with a specific host address and port.

        The attribute 'closeOnError' is set to 1 - which means that if
        a socket error occurs, the socket is silently closed and then
        reopened on the next logging call.
        """
        logging.Handler.__init__(self)
        self.host = host
        self.port = port
        self.sock = None
        self.closeOnError = 0
        self.retryTime = None
        #
        # Exponential backoff parameters.
        #
        self.retryStart = 1.0
        self.retryMax = 30.0
        self.retryFactor = 2.0 
Example 5
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def makePickle(self, record):
        """
        Pickles the record in binary format with a length prefix, and
        returns it ready for transmission across the socket.
        """
        ei = record.exc_info
        if ei:
            # just to get traceback text into record.exc_text ...
            dummy = self.format(record)
            record.exc_info = None  # to avoid Unpickleable error
        # See issue #14436: If msg or args are objects, they may not be
        # available on the receiving end. So we convert the msg % args
        # to a string, save it as msg and zap the args.
        d = dict(record.__dict__)
        d['msg'] = record.getMessage()
        d['args'] = None
        s = cPickle.dumps(d, 1)
        if ei:
            record.exc_info = ei  # for next handler
        slen = struct.pack(">L", len(s))
        return slen + s 
Example 6
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def emit(self, record):
        """
        Emit a record.

        Pickles the record and writes it to the socket in binary format.
        If there is an error with the socket, silently drop the packet.
        If there was a problem with the socket, re-establishes the
        socket.
        """
        try:
            s = self.makePickle(record)
            self.send(s)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record) 
Example 7
Project: pyblish-win   Author: pyblish   File: ftplib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
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 
Example 8
Project: pyblish-win   Author: pyblish   File: ftplib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def retrbinary(self, cmd, callback, blocksize=8192, rest=None):
        """Retrieve data in binary mode.  A new port is created for you.

        Args:
          cmd: A RETR command.
          callback: A single parameter callable to be called on each
                    block of data read.
          blocksize: The maximum number of bytes to read from the
                     socket at one time.  [default: 8192]
          rest: Passed to transfercmd().  [default: None]

        Returns:
          The response code.
        """
        self.voidcmd('TYPE I')
        conn = self.transfercmd(cmd, rest)
        while 1:
            data = conn.recv(blocksize)
            if not data:
                break
            callback(data)
        conn.close()
        return self.voidresp() 
Example 9
Project: pyblish-win   Author: pyblish   File: SocketServer.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def serve_forever(self, poll_interval=0.5):
        """Handle one request at a time until shutdown.

        Polls for shutdown every poll_interval seconds. Ignores
        self.timeout. If you need to do periodic tasks, do them in
        another thread.
        """
        self.__is_shut_down.clear()
        try:
            while not self.__shutdown_request:
                # XXX: Consider using another file descriptor or
                # connecting to the socket to wake this up instead of
                # polling. Polling reduces our responsiveness to a
                # shutdown request and wastes cpu at all other times.
                r, w, e = _eintr_retry(select.select, [self], [], [],
                                       poll_interval)
                if self in r:
                    self._handle_request_noblock()
        finally:
            self.__shutdown_request = False
            self.__is_shut_down.set() 
Example 10
Project: pyblish-win   Author: pyblish   File: SocketServer.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def handle_request(self):
        """Handle one request, possibly blocking.

        Respects self.timeout.
        """
        # Support people who used socket.settimeout() to escape
        # handle_request before self.timeout was available.
        timeout = self.socket.gettimeout()
        if timeout is None:
            timeout = self.timeout
        elif self.timeout is not None:
            timeout = min(timeout, self.timeout)
        fd_sets = _eintr_retry(select.select, [self], [], [], timeout)
        if not fd_sets[0]:
            self.handle_timeout()
            return
        self._handle_request_noblock() 
Example 11
Project: pyblish-win   Author: pyblish   File: smtplib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def connect(self, host='localhost', port=0):
        """Connect to the LMTP daemon, on either a Unix or a TCP socket."""
        if host[0] != '/':
            return SMTP.connect(self, host, port)

        # Handle Unix-domain sockets.
        try:
            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.sock.connect(host)
        except socket.error:
            if self.debuglevel > 0:
                print>>stderr, 'connect fail:', host
            if self.sock:
                self.sock.close()
            self.sock = None
            raise
        (code, msg) = self.getreply()
        if self.debuglevel > 0:
            print>>stderr, "connect:", msg
        return (code, msg)


# Test the sendmail method, which tests most of the others.
# Note: This always sends to localhost. 
Example 12
Project: pyblish-win   Author: pyblish   File: webbrowser.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _find_grail_rc(self):
        import glob
        import pwd
        import socket
        import tempfile
        tempdir = os.path.join(tempfile.gettempdir(),
                               ".grail-unix")
        user = pwd.getpwuid(os.getuid())[0]
        filename = os.path.join(tempdir, user + "-*")
        maybes = glob.glob(filename)
        if not maybes:
            return None
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        for fn in maybes:
            # need to PING each one until we find one that's live
            try:
                s.connect(fn)
            except socket.error:
                # no good; attempt to clean it out, but don't fail:
                try:
                    os.unlink(fn)
                except IOError:
                    pass
            else:
                return s 
Example 13
Project: unicorn-hat-hd   Author: pimoroni   File: show_my_ip.py    MIT License 5 votes vote down vote up
def get_ip():
    # get IP address
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 80))
    my_ip = s.getsockname()[0]
    print(my_ip)
    s.close()
    return my_ip 
Example 14
Project: flexnet   Author: ressy   File: client.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def connect(self):
        """Open TCP connection to self.server at self.port"""
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.settimeout(10)
        self.s.connect((self.server, self.port)) 
Example 15
Project: fs_image   Author: facebookincubator   File: yum_dnf_from_snapshot.py    MIT License 5 votes vote down vote up
def _make_socket_and_send_via(*, unix_sock_fd):
    '''
    Creates a TCP stream socket and sends it elsewhere via the provided Unix
    domain socket file descriptor.  This is useful for obtaining a socket
    that belongs to a different network namespace (i.e.  creating a socket
    inside a container, but binding it from outside the container).

    IMPORTANT: This code must not write anything to stdout, the fd can be 1.
    '''
    # NB: Some code here is (sort of) copy-pasta'd in `send_fds_and_run.py`,
    # but it's not obviously worthwhile to reuse it here.
    return ['python3', '-c', textwrap.dedent('''\
    import array, socket, sys

    def send_fds(sock, msg: bytes, fds: 'List[int]'):
        num_sent = sock.sendmsg([msg], [(
            socket.SOL_SOCKET, socket.SCM_RIGHTS,
            array.array('i', fds).tobytes(),
            # Future: is `flags=socket.MSG_NOSIGNAL` a good idea?
        )])
        assert len(msg) == num_sent, (msg, num_sent)

    # Make a socket in this netns, and send it to the parent.
    with socket.socket(fileno=''' + str(unix_sock_fd) + ''') as lsock:
        print(f'Sending FD to parent', file=sys.stderr)
        lsock.settimeout(''' + str(FD_UNIX_SOCK_TIMEOUT) + ''')
        with lsock.accept()[0] as csock, socket.socket(
            socket.AF_INET, socket.SOCK_STREAM
        ) as inet_sock:
            csock.settimeout(''' + str(FD_UNIX_SOCK_TIMEOUT) + ''')
            send_fds(csock, b'ohai', [inet_sock.fileno()])
    ''')] 
Example 16
Project: fs_image   Author: facebookincubator   File: test_repo_server.py    MIT License 5 votes vote down vote up
def repo_server_thread(self, location_to_obj):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(('127.0.0.1', 0))
        with repo_server(sock, location_to_obj, self.storage) as httpd:
            httpd.server_activate()
            thread = threading.Thread(name='RpSrv', target=httpd.serve_forever)
            thread.start()
            try:
                yield sock.getsockname()
            finally:
                httpd.shutdown()
                thread.join()

    # This validates a GET + headers, but not any of the storage retrieval. 
Example 17
Project: fs_image   Author: facebookincubator   File: repo_server.py    MIT License 5 votes vote down vote up
def __init__(self, sock: socket.socket, RequestHandlerClass):
        '''
        We just listen on `sock`. It may or may not be bound to any host or
        port **yet** -- and in fact, the binding will be done by another
        process on our behalf.
        '''
        # No server address since nothing actually needs to know it.
        super().__init__(None, RequestHandlerClass)
        self.socket = sock

    # This is only here as part of the BaseServer API, never to be run. 
Example 18
Project: fs_image   Author: facebookincubator   File: repo_server.py    MIT License 5 votes vote down vote up
def server_bind(self):  # pragma: no cover
        raise AssertionError(
            'self.socket must be bound externally before self.server_activate'
        ) 
Example 19
Project: fs_image   Author: facebookincubator   File: repo_server.py    MIT License 5 votes vote down vote up
def fileno(self):
        return self.socket.fileno() 
Example 20
Project: fs_image   Author: facebookincubator   File: repo_server.py    MIT License 5 votes vote down vote up
def get_request(self):
        return self.socket.accept() 
Example 21
Project: fs_image   Author: facebookincubator   File: common.py    MIT License 5 votes vote down vote up
def listen_temporary_unix_socket() -> Iterator[Tuple[str, socket.socket]]:
    # Hardcoding /tmp is ugly, but Buck sets $TMP to fairly long paths,
    # which can cause `AF_UNIX path too long`.
    with tempfile.TemporaryDirectory(dir='/tmp') as td, \
            socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as lsock:
        sock_path = os.path.join(td, 'sock')
        lsock.bind(sock_path)
        lsock.listen()
        yield sock_path, lsock 
Example 22
Project: fs_image   Author: facebookincubator   File: common.py    MIT License 5 votes vote down vote up
def recv_fds_from_unix_sock(sock_path, max_fds):
    with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as conn_sock:
        # Don't wait forever if the `send_fds` side crashes.  This is 3
        # minutes so we still make progress on overloaded hosts.
        conn_sock.settimeout(FD_UNIX_SOCK_TIMEOUT)
        conn_sock.connect(sock_path)
        ignored_msg_len = 128
        _msg, fds = recv_fds(conn_sock, ignored_msg_len, max_fds)
        return fds 
Example 23
Project: tom-bot   Author: maartenberg   File: rpc.py    MIT License 5 votes vote down vote up
def rpc_call(command, *args):
    ''' Call a function via the RPC socket. '''
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('localhost', 10666))
    if args:
        cmd = '{}\x1c{}'.format(command, '\x1c'.join(args))
    else:
        cmd = command
    LOGGER.debug(cmd)
    sock.sendall(cmd)
    resp = sock.recv(1024)
    sock.close()
    LOGGER.debug(resp)
    return resp 
Example 24
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def makeSocket(self, timeout=1):
        """
        A factory method which allows subclasses to define the precise
        type of socket they want.
        """
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if hasattr(s, 'settimeout'):
            s.settimeout(timeout)
        s.connect((self.host, self.port))
        return s 
Example 25
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def createSocket(self):
        """
        Try to create a socket, using an exponential backoff with
        a max retry time. Thanks to Robert Olson for the original patch
        (SF #815911) which has been slightly refactored.
        """
        now = time.time()
        # Either retryTime is None, in which case this
        # is the first time back after a disconnect, or
        # we've waited long enough.
        if self.retryTime is None:
            attempt = 1
        else:
            attempt = (now >= self.retryTime)
        if attempt:
            try:
                self.sock = self.makeSocket()
                self.retryTime = None # next time, no delay before trying
            except socket.error:
                #Creation failed, so set the retry time and return.
                if self.retryTime is None:
                    self.retryPeriod = self.retryStart
                else:
                    self.retryPeriod = self.retryPeriod * self.retryFactor
                    if self.retryPeriod > self.retryMax:
                        self.retryPeriod = self.retryMax
                self.retryTime = now + self.retryPeriod 
Example 26
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def send(self, s):
        """
        Send a pickled string to the socket.

        This function allows for partial sends which can happen when the
        network is busy.
        """
        if self.sock is None:
            self.createSocket()
        #self.sock can be None either because we haven't reached the retry
        #time yet, or because we have reached the retry time and retried,
        #but are still unable to connect.
        if self.sock:
            try:
                if hasattr(self.sock, "sendall"):
                    self.sock.sendall(s)
                else:
                    sentsofar = 0
                    left = len(s)
                    while left > 0:
                        sent = self.sock.send(s[sentsofar:])
                        sentsofar = sentsofar + sent
                        left = left - sent
            except socket.error:
                self.sock.close()
                self.sock = None  # so we can call createSocket next time 
Example 27
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def close(self):
        """
        Closes the socket.
        """
        self.acquire()
        try:
            if self.sock:
                self.sock.close()
                self.sock = None
        finally:
            self.release()
        logging.Handler.close(self) 
Example 28
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def makeSocket(self):
        """
        The factory method of SocketHandler is here overridden to create
        a UDP socket (SOCK_DGRAM).
        """
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return s 
Example 29
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def send(self, s):
        """
        Send a pickled string to a socket.

        This function no longer allows for partial sends which can happen
        when the network is busy - UDP does not guarantee delivery and
        can deliver packets out of sequence.
        """
        if self.sock is None:
            self.createSocket()
        self.sock.sendto(s, (self.host, self.port)) 
Example 30
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
                 facility=LOG_USER, socktype=None):
        """
        Initialize a handler.

        If address is specified as a string, a UNIX socket is used. To log to a
        local syslogd, "SysLogHandler(address="/dev/log")" can be used.
        If facility is not specified, LOG_USER is used. If socktype is
        specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific
        socket type will be used. For Unix sockets, you can also specify a
        socktype of None, in which case socket.SOCK_DGRAM will be used, falling
        back to socket.SOCK_STREAM.
        """
        logging.Handler.__init__(self)

        self.address = address
        self.facility = facility
        self.socktype = socktype

        if isinstance(address, basestring):
            self.unixsocket = 1
            self._connect_unixsocket(address)
        else:
            self.unixsocket = 0
            if socktype is None:
                socktype = socket.SOCK_DGRAM
            self.socket = socket.socket(socket.AF_INET, socktype)
            if socktype == socket.SOCK_STREAM:
                self.socket.connect(address)
            self.socktype = socktype
        self.formatter = None 
Example 31
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def close (self):
        """
        Closes the socket.
        """
        self.acquire()
        try:
            if self.unixsocket:
                self.socket.close()
        finally:
            self.release()
        logging.Handler.close(self) 
Example 32
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def emit(self, record):
        """
        Emit a record.

        The record is formatted, and then sent to the syslog server. If
        exception information is present, it is NOT sent to the server.
        """
        try:
            msg = self.format(record) + '\000'
            """
            We need to convert record level to lowercase, maybe this will
            change in the future.
            """
            prio = '<%d>' % self.encodePriority(self.facility,
                                                self.mapPriority(record.levelname))
            # Message is a string. Convert to bytes as required by RFC 5424
            if type(msg) is unicode:
                msg = msg.encode('utf-8')
            msg = prio + msg
            if self.unixsocket:
                try:
                    self.socket.send(msg)
                except socket.error:
                    self.socket.close() # See issue 17981
                    self._connect_unixsocket(self.address)
                    self.socket.send(msg)
            elif self.socktype == socket.SOCK_DGRAM:
                self.socket.sendto(msg, self.address)
            else:
                self.socket.sendall(msg)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record) 
Example 33
Project: pyblish-win   Author: pyblish   File: ftplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def sendeprt(self, host, port):
        '''Send a EPRT command with the current host and the given port number.'''
        af = 0
        if self.af == socket.AF_INET:
            af = 1
        if self.af == socket.AF_INET6:
            af = 2
        if af == 0:
            raise error_proto, 'unsupported address family'
        fields = ['', repr(af), host, repr(port), '']
        cmd = 'EPRT ' + '|'.join(fields)
        return self.voidcmd(cmd) 
Example 34
Project: pyblish-win   Author: pyblish   File: ftplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def makeport(self):
        '''Create a new socket and send a PORT command for it.'''
        err = None
        sock = None
        for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
            af, socktype, proto, canonname, sa = res
            try:
                sock = socket.socket(af, socktype, proto)
                sock.bind(sa)
            except socket.error, err:
                if sock:
                    sock.close()
                sock = None
                continue
            break 
Example 35
Project: pyblish-win   Author: pyblish   File: ftplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def transfercmd(self, cmd, rest=None):
        """Like ntransfercmd() but returns only the socket."""
        return self.ntransfercmd(cmd, rest)[0] 
Example 36
Project: pyblish-win   Author: pyblish   File: SocketServer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
        """Constructor.  May be extended, do not override."""
        BaseServer.__init__(self, server_address, RequestHandlerClass)
        self.socket = socket.socket(self.address_family,
                                    self.socket_type)
        if bind_and_activate:
            try:
                self.server_bind()
                self.server_activate()
            except:
                self.server_close()
                raise 
Example 37
Project: pyblish-win   Author: pyblish   File: SocketServer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def server_bind(self):
        """Called by constructor to bind the socket.

        May be overridden.

        """
        if self.allow_reuse_address:
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(self.server_address)
        self.server_address = self.socket.getsockname() 
Example 38
Project: pyblish-win   Author: pyblish   File: SocketServer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def server_activate(self):
        """Called by constructor to activate the server.

        May be overridden.

        """
        self.socket.listen(self.request_queue_size) 
Example 39
Project: pyblish-win   Author: pyblish   File: SocketServer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def server_close(self):
        """Called to clean-up the server.

        May be overridden.

        """
        self.socket.close() 
Example 40
Project: pyblish-win   Author: pyblish   File: SocketServer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def fileno(self):
        """Return socket file number.

        Interface required by select().

        """
        return self.socket.fileno() 
Example 41
Project: pyblish-win   Author: pyblish   File: SocketServer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def shutdown_request(self, request):
        """Called to shutdown and close an individual request."""
        try:
            #explicitly shutdown.  socket.close() merely releases
            #the socket and waits for GC to perform the actual close.
            request.shutdown(socket.SHUT_WR)
        except socket.error:
            pass #some platforms may raise ENOTCONN here
        self.close_request(request) 
Example 42
Project: pyblish-win   Author: pyblish   File: SocketServer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_request(self):
        data, client_addr = self.socket.recvfrom(self.max_packet_size)
        return (data, self.socket), client_addr 
Example 43
Project: pyblish-win   Author: pyblish   File: SocketServer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setup(self):
        self.connection = self.request
        if self.timeout is not None:
            self.connection.settimeout(self.timeout)
        if self.disable_nagle_algorithm:
            self.connection.setsockopt(socket.IPPROTO_TCP,
                                       socket.TCP_NODELAY, True)
        self.rfile = self.connection.makefile('rb', self.rbufsize)
        self.wfile = self.connection.makefile('wb', self.wbufsize) 
Example 44
Project: pyblish-win   Author: pyblish   File: SocketServer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def finish(self):
        if not self.wfile.closed:
            try:
                self.wfile.flush()
            except socket.error:
                # An final socket error may have occurred here, such as
                # the local error ECONNABORTED.
                pass
        self.wfile.close()
        self.rfile.close() 
Example 45
Project: pyblish-win   Author: pyblish   File: SocketServer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setup(self):
        try:
            from cStringIO import StringIO
        except ImportError:
            from StringIO import StringIO
        self.packet, self.socket = self.request
        self.rfile = StringIO(self.packet)
        self.wfile = StringIO() 
Example 46
Project: pyblish-win   Author: pyblish   File: smtplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, host='', port=0, local_hostname=None,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
        """Initialize a new instance.

        If specified, `host' is the name of the remote host to which to
        connect.  If specified, `port' specifies the port to which to connect.
        By default, smtplib.SMTP_PORT is used.  If a host is specified the
        connect method is called, and if it returns anything other than a
        success code an SMTPConnectError is raised.  If specified,
        `local_hostname` is used as the FQDN of the local host for the
        HELO/EHLO command.  Otherwise, the local hostname is found using
        socket.getfqdn().

        """
        self.timeout = timeout
        self.esmtp_features = {}
        if host:
            (code, msg) = self.connect(host, port)
            if code != 220:
                raise SMTPConnectError(code, msg)
        if local_hostname is not None:
            self.local_hostname = local_hostname
        else:
            # RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and
            # if that can't be calculated, that we should use a domain literal
            # instead (essentially an encoded IP address like [A.B.C.D]).
            fqdn = socket.getfqdn()
            if '.' in fqdn:
                self.local_hostname = fqdn
            else:
                # We can't find an fqdn hostname, so use a domain literal
                addr = '127.0.0.1'
                try:
                    addr = socket.gethostbyname(socket.gethostname())
                except socket.gaierror:
                    pass
                self.local_hostname = '[%s]' % addr 
Example 47
Project: pyblish-win   Author: pyblish   File: smtplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_socket(self, host, port, timeout):
        # This makes it simpler for SMTP_SSL to use the SMTP connect code
        # and just alter the socket connection bit.
        if self.debuglevel > 0:
            print>>stderr, 'connect:', (host, port)
        return socket.create_connection((host, port), timeout) 
Example 48
Project: pyblish-win   Author: pyblish   File: smtplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def connect(self, host='localhost', port=0):
        """Connect to a host on a given port.

        If the hostname ends with a colon (`:') followed by a number, and
        there is no port specified, that suffix will be stripped off and the
        number interpreted as the port number to use.

        Note: This method is automatically invoked by __init__, if a host is
        specified during instantiation.

        """
        if not port and (host.find(':') == host.rfind(':')):
            i = host.rfind(':')
            if i >= 0:
                host, port = host[:i], host[i + 1:]
                try:
                    port = int(port)
                except ValueError:
                    raise socket.error, "nonnumeric port"
        if not port:
            port = self.default_port
        if self.debuglevel > 0:
            print>>stderr, 'connect:', (host, port)
        self.sock = self._get_socket(host, port, self.timeout)
        (code, msg) = self.getreply()
        if self.debuglevel > 0:
            print>>stderr, "connect:", msg
        return (code, msg) 
Example 49
Project: pyblish-win   Author: pyblish   File: smtplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def send(self, str):
        """Send `str' to the server."""
        if self.debuglevel > 0:
            print>>stderr, 'send:', repr(str)
        if hasattr(self, 'sock') and self.sock:
            try:
                self.sock.sendall(str)
            except socket.error:
                self.close()
                raise SMTPServerDisconnected('Server not connected')
        else:
            raise SMTPServerDisconnected('please run connect() first') 
Example 50
Project: pyblish-win   Author: pyblish   File: smtplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, host='', port=0, local_hostname=None,
                     keyfile=None, certfile=None,
                     timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
            self.keyfile = keyfile
            self.certfile = certfile
            SMTP.__init__(self, host, port, local_hostname, timeout)