本文整理汇总了Python中usocket.socket方法的典型用法代码示例。如果您正苦于以下问题:Python usocket.socket方法的具体用法?Python usocket.socket怎么用?Python usocket.socket使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类usocket
的用法示例。
在下文中一共展示了usocket.socket方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_server
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [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: wan_ok
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [as 别名]
def wan_ok(self,
packet=b'$\x1a\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01'):
if not self.isconnected(): # WiFi is down
return False
length = 32 # DNS query and response packet size
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setblocking(False)
s.connect(('8.8.8.8', 53))
await asyncio.sleep(1)
try:
await self._as_write(packet, sock=s)
await asyncio.sleep(2)
res = await self._as_read(length, s)
if len(res) == length:
return True # DNS response size OK
except OSError: # Timeout on read: no connectivity.
return False
finally:
s.close()
return False
示例3: main
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [as 别名]
def main(use_stream=True):
while True:
d.measure()
data = b"api_key="+ API_KEY + "&field1=" + str(d.temperature()) + "&field2=" + str(d.humidity())
s = _socket.socket()
ai = _socket.getaddrinfo(HOST, 443)
addr = ai[0][-1]
s.connect(addr)
s = ssl.wrap_socket(s)
s.write("POST /update HTTP/1.0\r\n")
s.write("Host: " + HOST + "\r\n")
s.write("Content-Length: " + str(len(data)) + "\r\n\r\n")
s.write(data)
print(s.read(128))
s.close()
time.sleep(60)
示例4: socket_connect
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [as 别名]
def socket_connect(self):
if self.sock is not None:
self.sock.close()
try:
self.sock = socket.socket()
addr = socket.getaddrinfo(self.server, self.port)
if addr == []:
if self.addr_save:
try:
self.socket_connect(self.addr_save)
return
except:
raise OSError('addr get fail')
addr = addr[0][-1]
self.addr_save = addr
self.sock.connect(addr)
return True
except OSError:
return False
示例5: subscribe
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [as 别名]
def subscribe(self, topic, qos=0):
assert self.cb is not None, "Subscribe callback is not set"
self.sock.setblocking(True)
pkt = bytearray(b"\x82\0\0\0")
self.pid += 1
struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid)
#print(hex(len(pkt)), hexlify(pkt, ":"))
self.sock.write(pkt)
self._send_str(topic)
self.sock.write(qos.to_bytes(1, "little"))
# print("simple --> wait socket msg")
while 1:
op = self.wait_msg()
if op == 0x90:
resp = self.sock.read(4)
#print(resp)
assert resp[1] == pkt[2] and resp[2] == pkt[3]
if resp[3] == 0x80:
raise MQTTException(resp[3])
# print("simple --> wait socket finish")
return
示例6: poll
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [as 别名]
def poll(self, timeout=100):
if self.use_poll:
ready = self.poller.poll(timeout)
else:
ready = []
if len(self.targets) > 0:
(rlist, wlist, xlist) = select.select(
self.targets.keys(), [], [], timeout
)
ready = [(x, None) for x in rlist]
for one_ready in ready:
target = self.targets.get(one_ready[0].fileno(), None)
dbg("Targets %s" % str(self.targets.keys()))
if target:
# dbg("get socket with fileno: %s" % str(one_ready[0].fileno()) + " len: %s" % len(one_ready) + " selected: %s " % str(target.fileno()) )
# update time
target.do_read(one_ready[0])
示例7: go
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [as 别名]
def go(cls, to_secs, data, verbose, c_sock, s_sock, expected):
client_id, init_str = data.split('\n', 1)
verbose and print('Got connection from client', client_id)
if cls._server_sock is None: # 1st invocation
cls._server_sock = s_sock
cls._expected.update(expected)
if client_id in cls._conns: # Old client, new socket
if cls._conns[client_id].status():
print('Duplicate client {} ignored.'.format(client_id))
c_sock.close()
else: # Reconnect after failure
cls._conns[client_id]._reconnect(c_sock)
else: # New client: instantiate Connection
Connection(to_secs, c_sock, client_id, init_str, verbose)
# Server-side app waits for a working connection
示例8: run
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [as 别名]
def run():
global success
ok = True
try:
while ok:
res = poller.ipoll(10)
for sock, ev in res:
if ev & select.POLLIN:
r = sock.readline()
print(ev, r)
# A server outage prints 1, b'' forever on ESP8266 or Unix.
# If killer closes socket on ESP8266 ev is always 1,
# on Unix get ev == 32
# Never see 9 or 17 (base 10) which are the error responses expected by uasyncio
# (POLLIN & POLLERR or POLLIN & POLLHUP)
else: # The only way I can make it work (on Unix) is to quit on 32
print('Terminating event:', ev) # What is 32??
ok = False
break
await asyncio.sleep(0)
except OSError:
print('Got OSError') # Never happens
success = True # Detected socket closure or error by OSError or event
示例9: run
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [as 别名]
def run():
global success
ok = True
try:
while ok:
res = poller.ipoll(10)
for sock, ev in res:
if ev & select.POLLOUT:
r = sock.send(b'0123456789\n')
print(ev, r)
# On ESP8266 if another task closes the socket the poll object
# never triggers. uasyncio expects it to trigger with POLLHUP or
# (POLLOUT & POLLERR or POLLOUT & POLLHUP)
# If server fails gets OSError on both platforms.
else: # But on Unix socket closure produces ev == 32
print('Terminating event:', ev) # What is 32??
ok = False
break
await asyncio.sleep(1)
await asyncio.sleep(0)
except OSError:
print('Got OSError') # Happens on ESP8266 if server fails
success = True # Detected socket closure or error by OSError or event
示例10: open_connection
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [as 别名]
def open_connection(host, port):
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)
ss = Stream(s)
try:
s.connect(ai[-1])
except OSError as er:
if er.args[0] != 115: # EINPROGRESS
raise er
yield _io_queue.queue_write(s)
return ss, ss
# Class representing a TCP stream server, can be closed and used in "async with"
示例11: run
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [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).
示例12: __init__
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [as 别名]
def __init__(self, client_id, server, port=0, user=None, password=None, keepalive=0,
ssl=False, ssl_params={}):
if port == 0:
port = 8883 if ssl else 1883
self.client_id = client_id
self.sock = None
self.addr = socket.getaddrinfo(server, port)[0][-1]
self.ssl = ssl
self.ssl_params = ssl_params
self.pid = 0
self.cb = None
self.user = user
self.pswd = password
self.keepalive = keepalive
self.lw_topic = None
self.lw_msg = None
self.lw_qos = 0
self.lw_retain = False
示例13: __init__
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [as 别名]
def __init__(self, socket, owner) :
self.socket = socket
self.owner = owner
try :
line = readline(self.socket)
(version, status, _rest) = line.split(None, 2)
self.version = version
self.status = int(status)
self.headers = {}
while True:
line = readline(self.socket)
if not line or line == '\r\n' :
break
else :
(h, v) = HTTPResponse._parse_header(line)
self.headers[h] = v
except Exception as e :
logging.info("Error reading response: {}", e)
self.owner.close()
raise
示例14: run
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [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)
示例15: __init__
# 需要导入模块: import usocket [as 别名]
# 或者: from usocket import socket [as 别名]
def __init__(self, server, port):
# On ESP32 need to submit WiFi credentials
self._sta_if = network.WLAN(network.STA_IF)
self._sta_if.active(True)
# Note that the following blocks, potentially for seconds, owing to DNS lookup
self._addr = socket.getaddrinfo(server, port)[0][-1]
self._sock = socket.socket()
self._sock.setblocking(False)
try:
self._sock.connect(addr)
except OSError as e:
if e.args[0] not in BUSY_ERRORS:
raise
if ESP32: # Revolting kludge :-(
loop = asyncio.get_event_loop()
loop.create_task(self._idle_task())