Python socket.close() Examples

The following are 30 code examples of socket.close(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: wsgiserver3.py    From SalesforceXyTools with Apache License 2.0 8 votes vote down vote up
def respond(self):
        """Process the current request."""
        response = self.req.server.wsgi_app(self.env, self.start_response)
        try:
            for chunk in response:
                # "The start_response callable must not actually transmit
                # the response headers. Instead, it must store them for the
                # server or gateway to transmit only after the first
                # iteration of the application return value that yields
                # a NON-EMPTY string, or upon the application's first
                # invocation of the write() callable." (PEP 333)
                if chunk:
                    if isinstance(chunk, unicodestr):
                        chunk = chunk.encode('ISO-8859-1')
                    self.write(chunk)
        finally:
            if hasattr(response, "close"):
                response.close() 
Example #2
Source File: wsgiserver2.py    From SalesforceXyTools with Apache License 2.0 7 votes vote down vote up
def close(self):
        """Close the socket underlying this connection."""
        self.rfile.close()

        if not self.linger:
            # Python's socket module does NOT call close on the kernel socket
            # when you call socket.close(). We do so manually here because we
            # want this server to send a FIN TCP segment immediately. Note this
            # must be called *before* calling socket.close(), because the latter
            # drops its reference to the kernel socket.
            if hasattr(self.socket, '_sock'):
                self.socket._sock.close()
            self.socket.close()
        else:
            # On the other hand, sometimes we want to hang around for a bit
            # to make sure the client has a chance to read our entire
            # response. Skipping the close() calls here delays the FIN
            # packet until the socket object is garbage-collected later.
            # Someday, perhaps, we'll do the full lingering_close that
            # Apache does, but not today.
            pass 
Example #3
Source File: TCP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def stop(self):
		self._stop = True

		if self.threads:
			for t in self.threads:
				t.stop()
		
		# not so nice solution to get rid of the block of listen()
		# unfortunately close() does not help on the block
		try:
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			serverbind = self.config.get("Global", "serverbind")
			if serverbind == "0.0.0.0":
				# windows does not like to connect to 0.0.0.0
				serverbind = "127.0.0.1"

			server_socket.connect((serverbind, int(self.config.get(self.get_module_configname(), "serverport"))))
		except:
			pass

		return 
Example #4
Source File: __init__.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def run(self):
        self.server.stats['Worker Threads'][self.getName()] = self.stats
        try:
            self.ready = True
            while True:
                conn = self.server.requests.get()
                if conn is _SHUTDOWNREQUEST:
                    return
                
                self.conn = conn
                if self.server.stats['Enabled']:
                    self.start_time = time.time()
                try:
                    conn.communicate()
                finally:
                    conn.close()
                    if self.server.stats['Enabled']:
                        self.requests_seen += self.conn.requests_seen
                        self.bytes_read += self.conn.rfile.bytes_read
                        self.bytes_written += self.conn.wfile.bytes_written
                        self.work_time += time.time() - self.start_time
                        self.start_time = None
                    self.conn = None
        except (KeyboardInterrupt, SystemExit), exc:
            self.server.interrupt = exc 
Example #5
Source File: __init__.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def respond(self):
        response = self.req.server.wsgi_app(self.env, self.start_response)
        try:
            for chunk in response:
                # "The start_response callable must not actually transmit
                # the response headers. Instead, it must store them for the
                # server or gateway to transmit only after the first
                # iteration of the application return value that yields
                # a NON-EMPTY string, or upon the application's first
                # invocation of the write() callable." (PEP 333)
                if chunk:
                    if isinstance(chunk, unicode):
                        chunk = chunk.encode('ISO-8859-1')
                    self.write(chunk)
        finally:
            if hasattr(response, "close"):
                response.close() 
Example #6
Source File: SCTP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def stop(self):
		self._stop = True

		if self.threads:
			for t in self.threads:
				t.stop()
		
		# not so nice solution to get rid of the block of listen()
		# unfortunately close() does not help on the block
		try:
			server_socket = self.sctp.sctpsocket_tcp(socket.AF_INET)
			if self.config.get("Global", "serverbind") == "0.0.0.0":
				server_socket.connect(("127.0.0.1", int(self.config.get(self.get_module_configname(), "serverport"))))
			else:
				server_socket.connect((self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		except:
			pass

		return 
Example #7
Source File: SocketServer.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def finish(self):
        if not self.wfile.closed:
            try:
                self.wfile.flush()
            except socket.error:
                # A final socket error may have occurred here, such as
                # the local error ECONNABORTED.
                pass
        self.wfile.close()
        self.rfile.close() 
Example #8
Source File: SocketServer.py    From BinderFilter with MIT License 5 votes vote down vote up
def close_request(self, request):
        """Called to clean up an individual request."""
        request.close() 
Example #9
Source File: SocketServer.py    From oss-ftp with MIT License 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 #10
Source File: SocketServer.py    From oss-ftp with MIT License 5 votes vote down vote up
def close_request(self, request):
        # No need to close anything.
        pass 
Example #11
Source File: SocketServer.py    From oss-ftp with MIT License 5 votes vote down vote up
def server_close(self):
        """Called to clean-up the server.

        May be overridden.

        """
        self.socket.close() 
Example #12
Source File: SocketServer.py    From oss-ftp with MIT License 5 votes vote down vote up
def shutdown_request(self, request):
        """Called to shutdown and close an individual request."""
        self.close_request(request) 
Example #13
Source File: SocketServer.py    From BinderFilter with MIT License 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 #14
Source File: SocketServer.py    From BinderFilter with MIT License 5 votes vote down vote up
def close_request(self, request):
        # No need to close anything.
        pass 
Example #15
Source File: SocketServer.py    From oss-ftp with MIT License 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 #16
Source File: wsgiserver2.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def stop(self, timeout=5):
        # OmniMarkupPreviewer: Force shutdown without waiting too much
        while self._get_qsize() > 0:
            conn = self.get()
            if conn is not _SHUTDOWNREQUEST:
                conn.close()
        # Must shut down threads here so the code that calls
        # this method can know when all threads are stopped.
        for worker in self._threads:
            self._queue.put(_SHUTDOWNREQUEST)

        # Don't join currentThread (when stop is called inside a request).
        current = threading.currentThread()
        if timeout and timeout >= 0:
            endtime = time.time() + timeout
        while self._threads:
            worker = self._threads.pop()
            if worker is not current and worker.isAlive():
                try:
                    if timeout is None or timeout < 0:
                        worker.join()
                    else:
                        remaining_time = endtime - time.time()
                        if remaining_time > 0:
                            worker.join(remaining_time)
                        if worker.isAlive():
                            # We exhausted the timeout.
                            # Forcibly shut down the socket.
                            c = worker.conn
                            if c and not c.rfile.closed:
                                try:
                                    c.socket.shutdown(socket.SHUT_RD)
                                except TypeError:
                                    # pyOpenSSL sockets don't take an arg
                                    c.socket.shutdown()
                            worker.join()
                except (AssertionError,
                        # Ignore repeated Ctrl-C.
                        # See https://bitbucket.org/cherrypy/cherrypy/issue/691.
                        KeyboardInterrupt):
                    pass 
Example #17
Source File: wsgiserver2.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def run(self):
        self.server.stats['Worker Threads'][self.getName()] = self.stats
        try:
            self.ready = True
            while True:
                conn = self.server.requests.get()
                if conn is _SHUTDOWNREQUEST:
                    return

                self.conn = conn
                if self.server.stats['Enabled']:
                    self.start_time = time.time()
                try:
                    conn.communicate()
                finally:
                    conn.close()
                    if self.server.stats['Enabled']:
                        self.requests_seen += self.conn.requests_seen
                        self.bytes_read += self.conn.rfile.bytes_read
                        self.bytes_written += self.conn.wfile.bytes_written
                        self.work_time += time.time() - self.start_time
                        self.start_time = None
                    self.conn = None
        except (KeyboardInterrupt, SystemExit):
            exc = sys.exc_info()[1]
            self.server.interrupt = exc 
Example #18
Source File: TCP_generic.py    From XFLTReaT with MIT License 5 votes vote down vote up
def cleanup(self):
		try:
			self.comms_socket.close()
		except:
			pass

		if self.serverorclient:
			self.packetselector.delete_client(self.client) 
Example #19
Source File: wsgiserver2.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def simple_response(self, status, msg=""):
        """Write a simple response back to the client."""
        status = str(status)
        buf = [self.server.protocol + SPACE +
               status + CRLF,
               "Content-Length: %s\r\n" % len(msg),
               "Content-Type: text/plain\r\n"]

        if status[:3] in ("413", "414"):
            # Request Entity Too Large / Request-URI Too Long
            self.close_connection = True
            if self.response_protocol == 'HTTP/1.1':
                # This will not be true for 414, since read_request_line
                # usually raises 414 before reading the whole line, and we
                # therefore cannot know the proper response_protocol.
                buf.append("Connection: close\r\n")
            else:
                # HTTP/1.0 had no 413/414 status nor Connection header.
                # Emit 400 instead and trust the message body is enough.
                status = "400 Bad Request"

        buf.append(CRLF)
        if msg:
            if isinstance(msg, unicodestr):
                msg = msg.encode("ISO-8859-1")
            buf.append(msg)

        try:
            self.conn.wfile.sendall("".join(buf))
        except socket.error:
            x = sys.exc_info()[1]
            if x.args[0] not in socket_errors_to_ignore:
                raise 
Example #20
Source File: netutil_test.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def test_same_port_allocation(self):
        if "TRAVIS" in os.environ:
            self.skipTest("dual-stack servers often have port conflicts on travis")
        sockets = bind_sockets(0, "localhost")
        try:
            port = sockets[0].getsockname()[1]
            self.assertTrue(all(s.getsockname()[1] == port for s in sockets[1:]))
        finally:
            for sock in sockets:
                sock.close() 
Example #21
Source File: wsgiserver2.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def close(self):
        self.rfile.close() 
Example #22
Source File: wsgiserver2.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def close(self):
        self.rfile.close() 
Example #23
Source File: netutil_test.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        self.resolver.close()
        super(ThreadedResolverTest, self).tearDown() 
Example #24
Source File: wsgiserver3.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def stop(self, timeout=5):
        # OmniMarkupPreviewer: Force shutdown without waiting too much
        while self._get_qsize() > 0:
            conn = self.get()
            if conn is not _SHUTDOWNREQUEST:
                conn.close()
        # Must shut down threads here so the code that calls
        # this method can know when all threads are stopped.
        for worker in self._threads:
            self._queue.put(_SHUTDOWNREQUEST)

        # Don't join currentThread (when stop is called inside a request).
        current = threading.currentThread()
        if timeout and timeout >= 0:
            endtime = time.time() + timeout
        while self._threads:
            worker = self._threads.pop()
            if worker is not current and worker.isAlive():
                try:
                    if timeout is None or timeout < 0:
                        worker.join()
                    else:
                        remaining_time = endtime - time.time()
                        if remaining_time > 0:
                            worker.join(remaining_time)
                        if worker.isAlive():
                            # We exhausted the timeout.
                            # Forcibly shut down the socket.
                            c = worker.conn
                            if c and not c.rfile.closed:
                                try:
                                    c.socket.shutdown(socket.SHUT_RD)
                                except TypeError:
                                    # pyOpenSSL sockets don't take an arg
                                    c.socket.shutdown()
                            worker.join()
                except (AssertionError,
                        # Ignore repeated Ctrl-C.
                        # See https://bitbucket.org/cherrypy/cherrypy/issue/691.
                        KeyboardInterrupt):
                    pass 
Example #25
Source File: wsgiserver3.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def close(self):
        """Close the socket underlying this connection."""
        self.rfile.close()

        if not self.linger:
            # Python's socket module does NOT call close on the kernel socket
            # when you call socket.close(). We do so manually here because we
            # want this server to send a FIN TCP segment immediately. Note this
            # must be called *before* calling socket.close(), because the latter
            # drops its reference to the kernel socket.
            # Python 3 *probably* fixed this with socket._real_close; hard to tell.
##            self.socket._sock.close()
            self.socket.close()
        else:
            # On the other hand, sometimes we want to hang around for a bit
            # to make sure the client has a chance to read our entire
            # response. Skipping the close() calls here delays the FIN
            # packet until the socket object is garbage-collected later.
            # Someday, perhaps, we'll do the full lingering_close that
            # Apache does, but not today.
            pass 
Example #26
Source File: wsgiserver3.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def simple_response(self, status, msg=""):
        """Write a simple response back to the client."""
        status = str(status)
        buf = [bytes(self.server.protocol, "ascii") + SPACE +
               bytes(status, "ISO-8859-1") + CRLF,
               bytes("Content-Length: %s\r\n" % len(msg), "ISO-8859-1"),
               b"Content-Type: text/plain\r\n"]

        if status[:3] in ("413", "414"):
            # Request Entity Too Large / Request-URI Too Long
            self.close_connection = True
            if self.response_protocol == 'HTTP/1.1':
                # This will not be true for 414, since read_request_line
                # usually raises 414 before reading the whole line, and we
                # therefore cannot know the proper response_protocol.
                buf.append(b"Connection: close\r\n")
            else:
                # HTTP/1.0 had no 413/414 status nor Connection header.
                # Emit 400 instead and trust the message body is enough.
                status = "400 Bad Request"

        buf.append(CRLF)
        if msg:
            if isinstance(msg, unicodestr):
                msg = msg.encode("ISO-8859-1")
            buf.append(msg)

        try:
            self.conn.wfile.write(b"".join(buf))
        except socket.error:
            x = sys.exc_info()[1]
            if x.args[0] not in socket_errors_to_ignore:
                raise 
Example #27
Source File: wsgiserver3.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def close(self):
        self.rfile.close() 
Example #28
Source File: wsgiserver3.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def close(self):
        self.rfile.close() 
Example #29
Source File: wsgiserver3.py    From SalesforceXyTools with Apache License 2.0 5 votes vote down vote up
def close(self):
        self.rfile.close() 
Example #30
Source File: netutil_test.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def test_reuse_port(self):
        sockets = []  # type: List[socket.socket]
        socket, port = bind_unused_port(reuse_port=True)
        try:
            sockets = bind_sockets(port, "127.0.0.1", reuse_port=True)
            self.assertTrue(all(s.getsockname()[1] == port for s in sockets))
        finally:
            socket.close()
            for sock in sockets:
                sock.close()