本文整理汇总了Python中usocket.SOCK_STREAM属性的典型用法代码示例。如果您正苦于以下问题:Python usocket.SOCK_STREAM属性的具体用法?Python usocket.SOCK_STREAM怎么用?Python usocket.SOCK_STREAM使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类usocket
的用法示例。
在下文中一共展示了usocket.SOCK_STREAM属性的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_server
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SOCK_STREAM [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 SOCK_STREAM [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 SOCK_STREAM [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)
示例4: open_connection
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SOCK_STREAM [as 别名]
def open_connection(host, port, ssl=False):
if DEBUG and __debug__:
log.debug("open_connection(%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)
try:
s.connect(ai[-1])
except OSError as e:
if e.args[0] != uerrno.EINPROGRESS:
raise
if DEBUG and __debug__:
log.debug("open_connection: After connect")
yield IOWrite(s)
# if __debug__:
# assert s2.fileno() == s.fileno()
if DEBUG and __debug__:
log.debug("open_connection: After iowait: %s", s)
if ssl:
print("Warning: uasyncio SSL support is alpha")
import ussl
s.setblocking(True)
s2 = ussl.wrap_socket(s)
s.setblocking(False)
return StreamReader(s, s2), StreamWriter(s2, {})
return StreamReader(s), StreamWriter(s, {})
示例5: _tcp_server
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SOCK_STREAM [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()
示例6: __init__
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SOCK_STREAM [as 别名]
def __init__(
self,
listener,
poller,
port,
root_url,
server_version,
persistent_uuid,
other_headers=None,
ip_address=None,
):
self.listener = listener
self.poller = poller
self.port = port
self.root_url = root_url
self.server_version = server_version
self.persistent_uuid = persistent_uuid
self.uuid = machine.unique_id()
self.other_headers = other_headers
if ip_address:
self.ip_address = ip_address
else:
self.ip_address = upnp_device.local_ip_address()
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind((self.ip_address, self.port))
self.socket.listen(5)
if self.port == 0:
self.port = self.socket.getsockname()[1]
self.poller.add(self)
self.client_sockets = {}
self.listener.add_device(self)
示例7: run
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SOCK_STREAM [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).
示例8: open_connection
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SOCK_STREAM [as 别名]
def open_connection(host, port, ssl=False):
if DEBUG and __debug__:
log.debug("open_connection(%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)
try:
s.connect(ai[-1])
except OSError as e:
if e.args[0] != uerrno.EINPROGRESS:
raise
if DEBUG and __debug__:
log.debug("open_connection: After connect")
yield IOWrite(s)
# if __debug__:
# assert s2.fileno() == s.fileno()
if DEBUG and __debug__:
log.debug("open_connection: After iowait: %s", s)
if ssl:
print("Warning: uasyncio SSL support is alpha")
import ussl
s.setblocking(True)
s2 = ussl.wrap_socket(s)
s.setblocking(False)
return StreamReader(s, s2), StreamWriter(s2, {})
return StreamReader(s), StreamWriter(s, {})
示例9: https_test
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SOCK_STREAM [as 别名]
def https_test(hostname=AWS_ENDPOINT, sslp=SSL_PARAMS):
"""
Tests the HTTPS connectivity with AWS. Sends an HTTP request to obtain the
shadow of a thing and prints it.
:param hostname: AWS hostname to connect to.
:param sslp: SSL certificate parameters.
"""
# Connect to AWS.
s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM,
usocket.IPPROTO_SEC)
s.setblocking(False)
w = ussl.wrap_socket(s, **sslp)
print("- Connecting to AWS... ", end="")
w.connect((hostname, 8443))
print("[OK]")
# Send HTTP request.
print("- Sending shadow request for thing '%s'... " % THING_NAME, end="")
w.write(b'GET /things/%s/shadow HTTP/1.0\r\n'
b'Host: %s\r\n'
b'\r\n' % (THING_NAME, hostname))
print("[OK]")
# Read answer.
print("- Waiting for data... ", end="")
while True:
data = w.read(1024)
if data:
print("[OK]")
print("- Received shadow for thing '%s':" % THING_NAME)
print(64 * "-")
print(str(data, 'utf-8'))
print(64 * "-")
break
# Disconnect.
w.close()
print("- Done")
示例10: connect
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SOCK_STREAM [as 别名]
def connect(self, clean_session=True):
if self.ssl:
proto = socket.IPPROTO_SEC
else:
proto = socket.IPPROTO_TCP
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto)
if self.ssl:
import ussl
self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
self.sock.connect((self.server, self.port))
premsg = bytearray(b"\x10\0\0\0\0\0")
msg = bytearray(b"\x04MQTT\x04\x02\0\0")
sz = 10 + 2 + len(self.client_id)
msg[6] = clean_session << 1
if self.user is not None:
sz += 2 + len(self.user) + 2 + len(self.pswd)
msg[6] |= 0xC0
if self.keepalive:
assert self.keepalive < 65536
msg[7] |= self.keepalive >> 8
msg[8] |= self.keepalive & 0x00FF
if self.lw_topic:
sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
msg[6] |= self.lw_retain << 5
i = 1
while sz > 0x7f:
premsg[i] = (sz & 0x7f) | 0x80
sz >>= 7
i += 1
premsg[i] = sz
self.sock.write(premsg, i + 2)
self.sock.write(msg)
#print(hex(len(msg)), hexlify(msg, ":"))
self._send_str(self.client_id)
if self.lw_topic:
self._send_str(self.lw_topic)
self._send_str(self.lw_msg)
if self.user is not None:
self._send_str(self.user)
self._send_str(self.pswd)
resp = self.sock.read(4)
assert resp[0] == 0x20 and resp[1] == 0x02
if resp[3] != 0:
raise MQTTException(resp[3])
return resp[2] & 1
示例11: start_server
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import SOCK_STREAM [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()