asyncio中的非阻塞套接字connect()

时间:2018-09-29 14:05:46

标签: python-asyncio

Here是如何在myref.child("users").child(addingpatient.getUserId()).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { Users patient = dataSnapshot.getValue(Users.class); name.add(patient.getName()+" "+patient.getSurname()); sicks.add(patient.getSicks()); patientuid.add(patient.getUserId()); } PatientSelectionAdapter adapter= new PatientSelectionAdapter(getContext(),name,sicks,hastauid); rv.setAdapter(adapter); rv.setLayoutManager(new LinearLayoutManager(getContext())); } @Override public void onCancelled(DatabaseError error) {} }); 内进行非阻塞套接字连接(作为客户端)的示例。由于不建议使用该模块,建议使用onDataChange(),在asyncore中怎么做?创建套接字并在协程内部进行连接是同步进行的,并且会产生链接问题中所述的问题。

1 个答案:

答案 0 :(得分:0)

协程内部的连接看上去与该协程是同步的,但实际上相对于事件循环是异步的。这意味着您可以创建任意数量的并行运行的协程,而不会互相阻塞,而所有协程都在单个线程内运行。

如果您正在使用http,请使用examples查看aiohttp的并行下载。如果需要低级TCP连接,请查看the documentation中的示例,然后使用asyncio.gather并行运行它们:

async def talk(host):
    # wait until connection is established, but without blocking
    # other coroutines
    r, w = await asyncio.open_connection(host, 80)
    # use the streams r, w to talk to the server - for example, echo:
    while True:
        line = await r.readline()
        if not line:
            break
        w.write(line)
    w.close()

async def talk_many(hosts):
    coros = [talk(host) for host in hosts]
    await asyncio.gather(*coros)

asyncio.run(talk_many(["host1", "host2", ...])