本文整理汇总了Python中socket.socket.accept方法的典型用法代码示例。如果您正苦于以下问题:Python socket.accept方法的具体用法?Python socket.accept怎么用?Python socket.accept使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socket.socket
的用法示例。
在下文中一共展示了socket.accept方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Bus
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import accept [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 accept [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()
示例3: main
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import accept [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()
示例4: __init__
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import accept [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)
示例5: listen_for_data
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import accept [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)
示例6: SocketStream
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import accept [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()
示例7: main
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import accept [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
示例8: acceptUser
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import accept [as 别名]
def acceptUser(server : socket.socket):
global userSock
while (1):
(userSock, addressUser) = server.accept()
workWithUser(userSock)
示例9: SixjetServer
# 需要导入模块: from socket import socket [as 别名]
# 或者: from socket.socket import accept [as 别名]
class SixjetServer(Thread):
"""
A sixjet server. Server instances listen on both a specified port for
native sixjet commands and on an Autobus 2 service. They are created with
a function that will be used to write bytes to the parallel port; you'll
typically pass an instance of parallel.Parallel's setData method, but any
function accepting an integer will do.
"""
def __init__(self, write_function, port, bus, service_extra={}):
"""
Creates a new sixjet server. write_function is the function to use to
write data to the parallel port. port is the port on which the native
protocol listener should listen. service_extra is an optionally-empty
set of values that will be added to the Autobus 2's service info
dictionary. (Keys such as type will be added automatically, but such
keys present in service_extra will override the ones added
automatically.)
bus is the Autobus bus to use. You can usually just use:
from autobus2 import Bus
with Bus() as bus:
server = SixjetServer(..., bus, ...)
...
and things will work.
If write_function is None, a new parallel.Parallel instance will be
created, and its setData method used.
"""
Thread.__init__(self)
if write_function is None:
import parallel
self._parallel = parallel.Parallel()
write_function = self._parallel.setData
else:
self._parallel = None
# The event queue. Events can be pushed from any thread, but can only
# be read and processed from the SixjetServer's run method.
self.queue = Queue()
# The list of remote native-protocol connections. This must only be
# read and modified from the event thread.
self.connections = []
# The current states of all of the jets. This must only be read and
# modified from the event thread.
self.jet_states = [False] * 16
# True to shut down the server. This shouldn't be modified; instead,
# stop() should be called, which will post an event that sets this to
# True.
self.shut_down = False
# The server socket listening on the native protocol port
self.socket = Socket()
self.socket.bind(("", port))
# The Autobus service we're publishing
self.service = self.bus.create_service(
{"type": "sixjet", "sixjet.native_port": port},
from_py_object=AutobusService(self))
def listen_for_connections(self):
# We can just infinitely loop here as run() closes the socket after
# the event loop quits, which will cause an exception to be thrown here
while True:
s = self.socket.accept()
# The connection is just a dictionary for now. We're creating it
# before so that we can partial it into the input thread.
connection = Connection(self, s)
self.post_event({"event": "connected", "connection": connection})
connection.start()
def remote_message_received(self, connection, message):
self.post_event({"event": "message", "message": message})
def run(self):
# Start a socket listening for connections
Thread(target=self.listen_for_connections).start()
# Read events and process them in a loop.
while not self.shut_down:
# TODO: add support for scheduled tasks here, or use separate
# threads to post events when they happen. The latter would offer
# a better guarantee that events will be processed when they happen
# due to Python's sleep-waiting whenever using get with a timeout
# (which is due to attempting to wait on a condition with a timeout
# doing the aforementioned).
event = self.queue.get()
try:
self.handle_event(event)
except:
traceback.print_exc()
finally:
self.queue.task_done()
with print_exceptions:
self.socket.close()
def stop(self):
self.post_event({"event": "stop"})
def post_event(self, event):
self.queue.put(event)
def handle_event(self, event):
#.........这里部分代码省略.........