当前位置: 首页>>代码示例>>Python>>正文


Python socket.settimeout方法代码示例

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


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

示例1: run_client

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import settimeout [as 别名]
def run_client(server_address, server_port):
	# Ping a UDP pinger server running at the given address
	
	try:
		client_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM)

		# Time out after 1 second
		client_socket.settimeout(1.0)

		print("Pinging", str(server_address), "on port", server_port)

		for i in range(10):
			client_socket.sendto("".encode(), (server_address, server_port))

			try:
				time_start = time.time()
				_, _ = client_socket.recvfrom(1024)
				time_stop = time.time()
			except socket.timeout:
				print("Packet lost")
			else:
				print("RTT(Round trip time): {:.3f}ms".format((time_stop - time_start) * 1000))
	finally:
		client_socket.close()

	return 0
开发者ID:shenaishiren,项目名称:computer-network-a-top-approach,代码行数:28,代码来源:ping.py

示例2: send_mail

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import settimeout [as 别名]
def send_mail(sender_address, mail_server, receiver_address, message):
	try:
		client_socket = Socket(socket.AF_INET, socket.SOCK_STREAM)

		# set a 1 second timeout
		client_socket.settimeout(1.0)

		# connect to mail server
		client_socket.connect((mail_server, 25))

		def send(string):
			"""Helper function: fix newlines, encode and send a string"""
			final = string.replace("\n", "\r\n").encode("ascii")
			print "Sending " + final + "..."
			client_socket.send(final)

			return 0

		def recv_and_check(expected=250):
			"""Helper function: recive reply and check it's ok"""
			reply = client_socket.recv(2048)
			print "Got: ", reply

			code = int(reply.rstrip().split()[0])
			if code != expected:
				raise Exception(reply)

			return 0

		# get initial message from server
		recv_and_check(220)

		# send greeting
		send("HELO {}\n".format(sender_address.split("@")[1]))
		recv_and_check()

		# set sender address
		send("MAIL FROM: {}\n".format(sender_address))
		recv_and_check()

		# set receiver address
		send("RCPT TO: {}\n".format(receiver_address))
		recv_and_check()

		# prepare to send message
		send("DATA\n")
		recv_and_check(354)

		# send the message itself followed by terminator
		send("{}\n.\n".format(message))
		recv_and_check()

		send("QUIT\n")
		recv_and_check(221)

	finally:
		client_socket.close()


	return 0
开发者ID:shenaishiren,项目名称:computer-network-a-top-approach,代码行数:62,代码来源:mail-client.py

示例3: create_broadcast_sockets

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import settimeout [as 别名]
def create_broadcast_sockets():
    sender = Socket(AF_INET, SOCK_DGRAM)
    sender.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
    sender.setsockopt(SOL_SOCKET, SO_BROADCAST, True)
    sender.bind(("", 0))
    receiver = Socket(AF_INET, SOCK_DGRAM)
    receiver.settimeout(constants.broadcast_receiver_timeout)
    receiver.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
    receiver.setsockopt(SOL_SOCKET, SO_BROADCAST, True)
    receiver.bind(("", constants.broadcast_port))
    return sender, receiver
开发者ID:giflw,项目名称:afn-tools,代码行数:13,代码来源:discovery.py

示例4: run_client

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import settimeout [as 别名]
def run_client(server_address, server_port):
    """Ping a UDP pinger server running at the given address
    """

    client_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM)

    message = "Ping"

    client_socket.settimeout(1)

    for i in range(0, 10):
        start_time = time.time()
        client_socket.sendto(message, (server_address, server_port))
        try:
            data, server = client_socket.recvfrom(1024)
            end_time = time.time()
            elapsed = end_time - start_time
            print "%s, time: %f." % (data, elapsed)
        except:
            print "TIMEOUT!"
        time.sleep(1)
    return 0
开发者ID:rodrigoncalves,项目名称:myhttpd,代码行数:24,代码来源:ping.py

示例5: _is_client_request_ssl

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import settimeout [as 别名]
    def _is_client_request_ssl(cls, socket_: socket.socket) -> bool:
        while True:
            original_timeout = socket_.gettimeout()
            socket_.setblocking(False)

            try:
                data = socket_.recv(3, socket.MSG_PEEK)
            except OSError as error:
                if error.errno in (errno.EWOULDBLOCK, errno.EAGAIN):
                    yield from asyncio.sleep(0.01)
                else:
                    raise
            else:
                break
            finally:
                socket_.settimeout(original_timeout)

        _logger.debug('peeked data %s', data)
        if all(ord('A') <= char_code <= ord('Z') for char_code in data):
            return False
        else:
            return True
开发者ID:Super-Rad,项目名称:wpull,代码行数:24,代码来源:server.py

示例6: get_rtt

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import settimeout [as 别名]
def get_rtt(server_address, server_port):
    """Ping a UDP ping server running at the given address
    and show the ping status
    """
    server = (server_address, server_port)
    message = bytes("", 'UTF-8')

    client_socket = Socket(socket.AF_INET, socket.SOCK_DGRAM)
    client_socket.settimeout(1.0)

    try:
        initial_time = current_milli_time()
        client_socket.sendto(message, server)
        client_socket.recvfrom(1024)
        final_time = current_milli_time()

        rtt = final_time - initial_time
    except:
        rtt = -1

    client_socket.close()

    return rtt
开发者ID:LucianoPC,项目名称:ping,代码行数:25,代码来源:ping.py

示例7: __demodulate

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import settimeout [as 别名]
    def __demodulate(self, connection: socket.socket):
        connection.settimeout(0.1)
        time.sleep(self.TIMEOUT)

        total_data = []
        while True:
            try:
                data = connection.recv(65536)
                if data:
                    total_data.append(data)
                else:
                    break
            except socket.timeout:
                break

        if len(total_data) == 0:
            logger.error("Did not receive any data from socket.")

        arr = np.array(np.frombuffer(b"".join(total_data), dtype=np.complex64))
        signal = Signal("", "")
        signal._fulldata = arr
        pa = ProtocolAnalyzer(signal)
        pa.get_protocol_from_signal()
        return pa.plain_bits_str
开发者ID:jopohl,项目名称:urh,代码行数:26,代码来源:test_simulator.py

示例8: Bus

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import settimeout [as 别名]
class Bus(common.AutoClose):
    """
    An Autobus bus. Busses manage a set of published services, and allow
    connecting to other services. A single bus listens on a single TCP
    port and multiplexes all published services over it.
    
    Bus is a subclass of ServiceProvider; the service it provides is a service
    exposing information about what other services, events, functions, and
    objects are present. (This service is more commonly known as the
    introspection service.) You normally won't have to know this; instances of
    Bus register themselves as services with themselves, so you don't need to
    do anything to make the introspection service work.
    """
    def __init__(self, default_discoverers=True, default_publishers=True,
                 port=None):
        """
        Creates a new bus. The bus will listen on the specified port; if none
        is specified (which is the usual case), a port will be chosen from the
        ports not currently in use on this computer.
        
        If default_discoverers is True (the default), a default set of
        discoverers will be installed, and likewise for default_publishers.
        Right now, this simply installs a autobus2.discovery.BroadcastPublisher
        and autobus2.discovery.BroadcastDiscoverer. Others might be added in
        the future.
        """
        # Number of times this bus has been __enter__'d. Allows it to be used
        # as a re-entrant context manager.
        self.context_enters = 0
        if port is None:
            port = 0
        # True once close() has been called
        self.closed = False
        # The TCP server that will listen for connections
        self.server = Socket()
        self.server.bind(("", port))
        # TODO: make the backlog configurable
        self.server.listen(100)
        self.port = self.server.getsockname()[1]
        # Lock that nearly everything bus-related locks on
        self.lock = RLock()
        # PropertyTable whose keys are service ids and whose values are
        # instances of autobus2.local.LocalService
        self.local_services = PropertyTable()
        self.local_services.global_watch(self.local_service_changed)
        # Map of ids of discovered services to DiscoveredService instances
        self.discovered_services = {}
        self.discovery_listeners = []
        # List of (filter, function) tuples, where filter is an info object
        # filter and function is a function to be notified when a matching
        # service is created or deleted
        self.service_listeners = []
        # Set of RemoteConnection instances that have been bound to a service
        self.bound_connections = set()
        # Set of discoverers registered on this bus
        self.discoverers = set()
        # Set of publishers registered on this bus
        self.publishers = set()
        if default_discoverers:
            self.install_discoverer(discovery.BroadcastDiscoverer())
        if default_publishers:
            self.install_publisher(discovery.BroadcastPublisher())
        Thread(name="autobus2.Bus.accept_loop", target=self.accept_loop).start()
        # Disable the introspection service for now. I'm seeing what would
        # happen if I have per-service introspection functions and objects, so
        # I'm disabling the bus-wide introspection service.
        # self._create_introspection_service()
        #
        # Register the bus as a service on itself.
        self.create_service({"type": "autobus.details", "pid": os.getpid()}, _IntrospectionService(self))
    
    def accept_loop(self):
        """
        Called on a new thread to accept socket connections to this bus.
        """
        self.server.settimeout(1)
        while not self.closed:
            try:
                socket = None
                socket = self.server.accept()[0]
                self.setup_inbound_socket(socket)
            except SocketTimeout: # This happens when we time out, which is
                # normal. The 1-second timeout is to fix what appears to be a
                # bug with Windows not properly throwing an exception from
                # accept when another thread closes the socket.
                pass
            except: # This happens when the server socket is closed
                if socket:
                    socket.close() # Make sure it's /really/ closed on the
                    # off chance that something else caused the exception
                if not issubclass(sys.exc_type, SocketError): # Something else
                    # happened
                    print_exc()
                # print "Bus server died"
                return
    
    @synchronized_on("lock")
    def create_service(self, info, provider):
        """
        Creates a new service on this bus. info is the info object to use for
#.........这里部分代码省略.........
开发者ID:giflw,项目名称:afn-tools,代码行数:103,代码来源:__init__.py

示例9: wait_connect

# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import settimeout [as 别名]
    def wait_connect(self):
        if self.needQuit:
            return
        self.init_graphic()
        self.informBoard = dashboard.InformBoard((10, 25), 15)

        test = 0
        server = Socket(socket.AF_INET, socket.SOCK_STREAM)
        if not test:
            while 1:
                try:
                    server.bind(("", config.Port))
                    break
                except socket.error as e:
                    self.inform(str(e))
                    for event in pygame.event.get():
                        if event.type == QUIT:
                            self.quit()
                            break
                    self.render_connection()
                    sleep(1)
            server.listen(2)
            server.settimeout(0.0)

            player1 = Player(1, server)
        else:
            player1 = HumanPlayer(1)

        if self.add_human:
            player2 = HumanPlayer(2)
            # add handler for human player
            self.pyeventHandlers.append(player2)
        else:
            player2 = Player(2, server)

        players = [player1, player2, None]

        timer = pygame.time.Clock()
        # wait until connected 2 players
        finished = 0
        player = players[finished]
        try:
            self.inform("waiting for AI to connect...")
            while finished < 2:
                for event in pygame.event.get():
                    if event.type == QUIT:
                        self.quit()
                        break
                if self.needQuit:
                    break
                if player.connect():
                    self.add_player(player)
                    self.inform("AI %s connected" % (player.name))
                    finished += 1
                    player = players[finished]
                self.render_connection()
                timer.tick(10)
        except KeyboardInterrupt:
            server.close()
            return False
        server.close()

        return True
开发者ID:ZhanruiLiang,项目名称:MSRA-Python-Clone,代码行数:65,代码来源:shippo.py


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