本文整理汇总了Python中usocket.SO_REUSEADDR属性的典型用法代码示例。如果您正苦于以下问题:Python usocket.SO_REUSEADDR属性的具体用法?Python usocket.SO_REUSEADDR怎么用?Python usocket.SO_REUSEADDR使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类usocket
的用法示例。
在下文中一共展示了usocket.SO_REUSEADDR属性的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_server
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SO_REUSEADDR [as 别名]
def start_server(client_coro, host, port, backlog=10):
if DEBUG and __debug__:
log.debug("start_server(%s, %s)", host, port)
ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM)
ai = ai[0]
s = _socket.socket(ai[0], ai[1], ai[2])
s.setblocking(False)
s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
s.bind(ai[-1])
s.listen(backlog)
while True:
if DEBUG and __debug__:
log.debug("start_server: Before accept")
yield IORead(s)
if DEBUG and __debug__:
log.debug("start_server: After iowait")
s2, client_addr = s.accept()
s2.setblocking(False)
if DEBUG and __debug__:
log.debug("start_server: After accept: %s", s2)
extra = {"peername": client_addr}
yield client_coro(StreamReader(s2), StreamWriter(s2, extra))
示例2: run
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SO_REUSEADDR [as 别名]
def run(timeout, nconns=10, verbose=False):
addr = socket.getaddrinfo('0.0.0.0', PORT, 0, socket.SOCK_STREAM)[0][-1]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socks.append(s)
s.bind(addr)
s.listen(nconns)
verbose and print('Awaiting connection.')
while True:
yield asyncio.IORead(s) # Register socket for polling
conn, addr = s.accept()
conn.setblocking(False)
try:
idstr = await readline(conn, timeout)
verbose and print('Got connection from client', idstr)
socks.append(conn)
Connection.go(int(idstr), timeout, verbose, conn)
except OSError:
if conn is not None:
conn.close()
# A Connection persists even if client dies (minimise object creation).
# If client dies Connection is closed: .close() flags this state by closing its
# socket and setting .conn to None (.ok() == False).
示例3: run
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SO_REUSEADDR [as 别名]
def run(self, host='0.0.0.0', port=5000, debug=False):
self.debug = debug
s = socket.socket()
ai = socket.getaddrinfo(host, port)
addr = ai[0][-1]
if self.debug: # pragma: no cover
print('Starting {mode} server on {host}:{port}...'.format(
mode=concurrency_mode, host=host, port=port))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(5)
while True:
sock, addr = s.accept()
create_thread(self.dispatch_request, sock, addr)
示例4: run
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SO_REUSEADDR [as 别名]
def run(self, loop, port=8123):
addr = socket.getaddrinfo('0.0.0.0', port, 0, socket.SOCK_STREAM)[0][-1]
s_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # server socket
s_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s_sock.bind(addr)
s_sock.listen(5)
self.socks = [s_sock] # List of current sockets for .close()
print('Awaiting connection on port', port)
poller = select.poll()
poller.register(s_sock, select.POLLIN)
client_id = 1 # For user feedback
while True:
res = poller.poll(1) # 1ms block
if res: # Only s_sock is polled
c_sock, _ = s_sock.accept() # get client socket
loop.create_task(self.run_client(c_sock, client_id))
client_id += 1
await asyncio.sleep_ms(200)
示例5: main
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SO_REUSEADDR [as 别名]
def main():
led = machine.Pin(2, machine.Pin.OUT)
led.value(1)
s = socket.socket()
ai = socket.getaddrinfo("0.0.0.0", 8080)
addr = ai[0][-1]
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(5)
print("Listening, connect your browser to http://<this_host>:8080/")
counter = 0
while True:
res = s.accept()
client_s = res[0]
client_addr = res[1]
req = client_s.recv(1024)
cmd = getCommand(req)
print(cmd)
if (cmd == "/on"):
led.value(0)
elif (cmd == "/off"):
led.value(1)
client_s.send(CONTENT % counter)
client_s.close()
counter += 1
print()
示例6: _tcp_server
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SO_REUSEADDR [as 别名]
def _tcp_server(self, host, port, backlog):
"""TCP Server implementation.
Opens socket for accepting connection and
creates task for every new accepted connection
"""
addr = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0][-1]
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(False)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(addr)
sock.listen(backlog)
try:
while True:
yield asyncio.IORead(sock)
csock, caddr = sock.accept()
csock.setblocking(False)
# Start handler / keep it in the map - to be able to
# shutdown gracefully - by close all connections
self.processed_connections += 1
hid = id(csock)
handler = self._handler(asyncio.StreamReader(csock),
asyncio.StreamWriter(csock, {}))
self.conns[hid] = handler
self.loop.create_task(handler)
# In case of max concurrency reached - temporary pause server:
# 1. backlog must be greater than max_concurrency, otherwise
# client will got "Connection Reset"
# 2. Server task will be resumed whenever one active connection finished
if len(self.conns) == self.max_concurrency:
# Pause
yield False
except asyncio.CancelledError:
return
finally:
sock.close()
示例7: init_socket
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SO_REUSEADDR [as 别名]
def init_socket(self):
ok = True
self.ip = "239.255.255.250"
self.port = 1900
try:
# This is needed to join a multicast group
self.mreq = struct.pack("4sl", inet_aton(self.ip), INADDR_ANY)
# Set up server socket
self.ssock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self.ssock.bind(("", self.port))
except Exception as e:
dbg("WARNING: Failed to bind %s:%d: %s", (self.ip, self.port, e))
ok = False
try:
dbg(
"IP: "
+ str(socket.IPPROTO_IP)
+ " IP_ADD_MEMBERSHIP: "
+ str(socket.IP_ADD_MEMBERSHIP)
+ " mreq: "
+ str(self.mreq)
)
self.ssock.setsockopt(
socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self.mreq
)
except Exception as e:
dbg("WARNING: Failed to join multicast group!: " + str(e))
ok = False
except Exception as e:
dbg("Failed to initialize UPnP sockets!")
return False
if ok:
dbg("Listening for UPnP broadcasts")
示例8: run
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SO_REUSEADDR [as 别名]
def run(expected, verbose=False, port=8123, timeout=2000):
addr = socket.getaddrinfo('0.0.0.0', port, 0, socket.SOCK_STREAM)[0][-1]
s_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # server socket
s_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s_sock.bind(addr)
s_sock.listen(len(expected) + 2)
verbose and print('Awaiting connection.', port)
poller = select.poll()
poller.register(s_sock, select.POLLIN)
to_secs = timeout / 1000 # ms -> secs
while True:
res = poller.poll(1) # 1ms block
if res: # Only s_sock is polled
c_sock, _ = s_sock.accept() # get client socket
c_sock.setblocking(False)
try:
data = await _readid(c_sock, to_secs)
except OSError:
c_sock.close()
else:
Connection.go(to_secs, data, verbose, c_sock, s_sock,
expected)
await asyncio.sleep(0.2)
# A Connection persists even if client dies (minimise object creation).
# If client dies Connection is closed: ._close() flags this state by closing its
# socket and setting .sock to None (.status() == False).
示例9: _serve
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SO_REUSEADDR [as 别名]
def _serve(self, cb, host, port, backlog):
try:
import usocket as socket
except ImportError:
import socket
ai = socket.getaddrinfo(host, port)[0] # TODO this is blocking!
s = socket.socket()
s.setblocking(False)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(ai[-1])
s.listen(backlog)
self.task = cur_task
# Accept incoming connections
while True:
try:
yield _io_queue.queue_read(s)
except CancelledError:
# Shutdown server
s.close()
return
s2, addr = s.accept()
s2.setblocking(False)
s2s = Stream(s2, {'peername': addr})
create_task(cb(s2s, s2s))
# Helper function to start a TCP stream server, running as a new task
# TODO could use an accept-callback on socket read activity instead of creating a task
示例10: start
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SO_REUSEADDR [as 别名]
def start(self):
s = socket.socket()
ai = socket.getaddrinfo(self.ip, self.port)
addr = ai[0][-1]
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(5)
print('server started on %s:%s' % addr)
# main server loop
while True:
print('waiting for connection ...')
res = s.accept()
client_s = res[0]
print('accepted')
try:
# read the status line
status_line = client_s.readline().decode('utf-8').strip()
# content length
length = 0
# read all headers, and look for Content-Length header
# in order to read data from the request
headers = {}
while True:
h = client_s.readline()
if h == b"" or h == b"\r\n":
break
parts = h.decode('utf-8').strip().lower().split(':')
name = parts[0].strip()
value = parts[1].strip()
headers[name] = value
if name == 'content-length':
length = int(value)
# read data from the request
data = client_s.read(length).decode('utf-8')
# let the handler to process the request
self.handler.handle(client_s, status_line, headers, data)
client_s.close()
except Exception as e:
print(e)
raise e
示例11: start_server
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SO_REUSEADDR [as 别名]
def start_server(client_coro, host, port, backlog=10):
if DEBUG and __debug__:
log.debug("start_server(%s, %s)", host, port)
ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM)
ai = ai[0]
s = _socket.socket(ai[0], ai[1], ai[2])
s.setblocking(False)
s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
s.bind(ai[-1])
s.listen(backlog)
try:
while True:
try:
if DEBUG and __debug__:
log.debug("start_server: Before accept")
yield IORead(s)
if DEBUG and __debug__:
log.debug("start_server: After iowait")
s2, client_addr = s.accept()
s2.setblocking(False)
if DEBUG and __debug__:
log.debug("start_server: After accept: %s", s2)
extra = {"peername": client_addr}
# Detach the client_coro: put it on runq
yield client_coro(StreamReader(s2), StreamWriter(s2, extra))
s2 = None
except Exception as e:
if len(e.args)==0:
# This happens but shouldn't. Firmware bug?
# Handle exception as an unexpected unknown error:
# collect details here then close try to continue running
print('start_server:Unknown error: continuing')
sys.print_exception(e)
if not uerrno.errorcode.get(e.args[0], False):
# Handle exception as internal error: close and terminate
# handler (user must trap or crash)
print('start_server:Unexpected error: terminating')
raise
finally:
if s2:
s2.close()
s.close()