Python socket.close() Examples

The following are 30 code examples for showing how to use socket.close(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: XFLTReaT   Author: earthquake   File: TCP_generic.py    License: 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 2
Project: XFLTReaT   Author: earthquake   File: SCTP_generic.py    License: 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 3
Project: Faraday-Software   Author: FaradayRF   File: aprs.py    License: GNU General Public License v3.0 6 votes vote down vote up
def sendAPRSPacket(socket, packet):
    """
    Sends an APRS packet (just a string) to the socket specified. If an
    error occurs a False is returned while a True is returned if successful.
    On an error, the socket is closed as it is no longer useful.

    :param socket: APRS-IS server internet socket
    :param packet: String to be sent to APRS-IS
    :return: Boolean
    """

    try:
        socket.sendall(packet)
        return True

    except IOError as e:
        logger.error(e)
        socket.close()
        return False 
Example 4
Project: SalesforceXyTools   Author: exiahuang   File: wsgiserver3.py    License: Apache License 2.0 6 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 5
Project: SalesforceXyTools   Author: exiahuang   File: wsgiserver3.py    License: Apache License 2.0 6 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 6
Project: SalesforceXyTools   Author: exiahuang   File: wsgiserver2.py    License: Apache License 2.0 6 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 7
Project: nightmare   Author: joxeankoret   File: __init__.py    License: 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 8
Project: nightmare   Author: joxeankoret   File: __init__.py    License: 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 9
Project: XFLTReaT   Author: earthquake   File: TCP_generic.py    License: 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 10
Project: XFLTReaT   Author: earthquake   File: TCP_generic.py    License: MIT License 5 votes vote down vote up
def cleanup(self, socket):
		common.internal_print("Shutting down module: {0}".format(self.get_module_name()))
		socket.close()

		return 
Example 11
Project: XFLTReaT   Author: earthquake   File: SCTP_generic.py    License: MIT License 5 votes vote down vote up
def cleanup(self, socket):
		common.internal_print("Shutting down module: {0}".format(self.get_module_name()))
		socket.close()

		return 
Example 12
Project: XFLTReaT   Author: earthquake   File: packetselector.py    License: MIT License 5 votes vote down vote up
def delete_client(self, client):
		if client in self.clients:

			if self.os_type == common.OS_WINDOWS:
				import win32file

				try:
					win32file.CloseHandle(client.get_pipe_r())
					win32file.CloseHandle(client.get_pipe_w())
				except Exception as e:
					common.internal_print("Remove authenticated client: CloseHandle exception: {0}".format(e), -1)
			else:
				try:
					client.get_pipe_r_fd().close()
					client.get_pipe_w_fd().close()
				except Exception as e:
					common.internal_print("Remove authenticated client: os.close exception: {0}".format(e), -1)

			client.call_stopfp()
			self.clients.remove(client)

		return

	# This function should run from the point when the framework was started.
	# It runs as an infinite loop to read the packets off the tunnel.
	# When an IPv4 packet was found that will be selected and checked whether
	# it addresses a client in the client list. If a client was found, then the
	# packet will be written on that pipe. 
Example 13
Project: verge3d-blender-addon   Author: Soft8Soft   File: socketserver.py    License: GNU General Public License v3.0 5 votes vote down vote up
def shutdown_request(self, request):
        """Called to shutdown and close an individual request."""
        self.close_request(request) 
Example 14
Project: verge3d-blender-addon   Author: Soft8Soft   File: socketserver.py    License: GNU 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 15
Project: verge3d-blender-addon   Author: Soft8Soft   File: socketserver.py    License: GNU 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 16
Project: verge3d-blender-addon   Author: Soft8Soft   File: socketserver.py    License: GNU General Public License v3.0 5 votes vote down vote up
def close_request(self, request):
        """Called to clean up an individual request."""
        request.close() 
Example 17
Project: verge3d-blender-addon   Author: Soft8Soft   File: socketserver.py    License: GNU General Public License v3.0 5 votes vote down vote up
def close_request(self, request):
        # No need to close anything.
        pass 
Example 18
Project: misp42splunk   Author: remg427   File: socketserver.py    License: 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."""
        self.close_request(request) 
Example 19
Project: misp42splunk   Author: remg427   File: socketserver.py    License: 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 20
Project: misp42splunk   Author: remg427   File: socketserver.py    License: 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 21
Project: misp42splunk   Author: remg427   File: socketserver.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def close_request(self, request):
        """Called to clean up an individual request."""
        request.close() 
Example 22
Project: misp42splunk   Author: remg427   File: socketserver.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def close_request(self, request):
        # No need to close anything.
        pass 
Example 23
Project: misp42splunk   Author: remg427   File: socketserver.py    License: 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."""
        self.close_request(request) 
Example 24
Project: misp42splunk   Author: remg427   File: socketserver.py    License: 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 25
Project: misp42splunk   Author: remg427   File: socketserver.py    License: 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 26
Project: misp42splunk   Author: remg427   File: socketserver.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def close_request(self, request):
        """Called to clean up an individual request."""
        request.close() 
Example 27
Project: misp42splunk   Author: remg427   File: socketserver.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def close_request(self, request):
        # No need to close anything.
        pass 
Example 28
Project: tornado-zh   Author: tao12345666333   File: netutil_test.py    License: MIT License 5 votes vote down vote up
def tearDown(self):
        self.resolver.close()
        super(ThreadedResolverTest, self).tearDown() 
Example 29
Project: tornado-zh   Author: tao12345666333   File: netutil_test.py    License: MIT License 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(None, '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 30
Project: tornado-zh   Author: tao12345666333   File: netutil_test.py    License: MIT License 5 votes vote down vote up
def test_reuse_port(self):
        socket, port = bind_unused_port(reuse_port=True)
        try:
            sockets = bind_sockets(port, 'localhost', reuse_port=True)
            self.assertTrue(all(s.getsockname()[1] == port for s in sockets))
        finally:
            socket.close()
            for sock in sockets:
                sock.close()