本文整理汇总了Python中socket.socket.listen方法的典型用法代码示例。如果您正苦于以下问题:Python socket.listen方法的具体用法?Python socket.listen怎么用?Python socket.listen使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socket.socket
的用法示例。
在下文中一共展示了socket.listen方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Bus
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import listen [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
#.........这里部分代码省略.........
示例2: main
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import listen [as 别名]
def main():
register_builtin_interface()
server = Socket()
if len(sys.argv) > 1:
server_port = int(sys.argv[1])
else:
server_port = DEFAULT_PORT
print "Listening on port " + str(server_port)
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind(("", server_port))
server.listen(50)
Thread(target=process_event_queue).start()
print "\nAutobus has successfully started up."
try:
while True:
socket, address = server.accept()
connection = Connection(socket, address)
event_queue.put((connection.id, discard_args(connection.register)), block=True)
connection.start()
except KeyboardInterrupt:
print "KeyboardInterrupt received, shutting down"
event_queue.put((None, None), block=True)
print "Event queue has been notified to shut down"
except:
print "Unexpected exception occurred in the main loop, shutting down. Stack trace:"
print_exc()
event_queue.put((None, None), block=True)
print "Event queue has been notified to shut down"
server.close()
示例3: main
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import listen [as 别名]
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--port', '-p', default=8080, type=int,
help='Port to use')
args = parser.parse_args()
try:
server_socket = Socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, BUFFER_SIZE)
server_socket.bind(('', args.port))
server_socket.listen(1)
cache_dict = {}
print "Proxy server ready..."
while True:
try:
connection_socket = server_socket.accept()[0]
t = Thread(target=handle_http, args=[cache_dict, connection_socket])
t.setDaemon(1)
t.start()
t.join()
except socket.error, e:
print e
finally:
connection_socket.close()
示例4: listen
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import listen [as 别名]
def listen(self):
"""
Bind and listen.
:return: The open socket.
:rtype: socket.socket
"""
address = (self.host, self.port)
socket = Socket(AF_INET, SOCK_STREAM)
socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
socket.bind(address)
socket.listen(5)
log.info('listening on: %d', self.port)
return socket
示例5: __init__
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import listen [as 别名]
def __init__(self):
# Set up the interrupt socket
interrupt_server = Socket()
interrupt_server.bind(("localhost", 0))
interrupt_server.listen(1)
self.interrupt_writer = Socket()
self.interrupt_writer.setblocking(False)
self.interrupt_writer.connect("localhost", interrupt_server.getsockname()[1])
self.interrupt_reader = interrupt_server.accept()
interrupt_server.shutdown(SHUT_RDWR)
interrupt_server.close()
self.interrupt_reader.setblocking(False)
self.interrupt_writer.setblocking(False)
示例6: listen_for_data
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import listen [as 别名]
def listen_for_data(sock: socket.socket) -> None:
"""Make the socket listen for data forever."""
host = 'localhost'
port = 41401
sock.bind((host, port))
sock.listen(1)
while True:
print('Waiting...')
conn, addr = sock.accept()
print(f'Connection from {addr}')
if addr[0] != '127.0.0.1':
continue
with conn:
data = receive_all(conn)
parse_data(data)
示例7: SocketStream
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import listen [as 别名]
class SocketStream(Stream):
def __init__(self, port):
self.listener = Socket(AF_INET, SOCK_STREAM)
self.listener.bind(('', port))
def open(self):
self.listener.listen(1)
self.socket, address = self.listener.accept()
def read(self, size=1024):
return self.socket.recv(size)
def write(self, data):
self.socket.sendall(data)
def close(self):
self.socket.close()
self.listener.close()
示例8: main
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import listen [as 别名]
def main():
parser=argparse.ArgumentParser()
parser.add_argument('--port','-p',default=2000,type=int,help='port to use')
args=parser.parse_args()
server_socket=Socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server_socket.bind(('',args.port))
server_socket.listen(1)
print "server running"
while True:
connection_socket=server_socket.accept()[0]
request=connection_socket.recv(1024)
reply=http_handler(request)
connection_socket.send("HTTP/1.1 200 OK\n")
connection_socket.send("\n")
connection_socket.send(reply)
connection_socket.close()
print "received request"
print "reply sent"
return 0
示例9: Socket
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import listen [as 别名]
import socket as Net
from socket import socket as Socket
import os,re,sys
print Net.AF_INET,Net.SOCK_STREAM
s = Socket(Net.AF_INET,Net.SOCK_STREAM)
#get localhost name and ip address
localhostName = Net.gethostname()
localhostAddress = Net.gethostbyname(localhostName)
print localhostName , localhostAddress
try:
s.bind((localhostAddress,10010))
print 'bind succeed!'
s.listen(10)
print 'start to listen!'
except Exception as ex:
print 'Error' , ex
finally:
s.close()
print 'socket closed!'
示例10: wait_connect
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import listen [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