如何将WebSocket绑定到现有进程?

2024-09-30 01:30:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个应用程序,它将以用户身份连接到XMPP服务器,并公开用户通过websocket接收的消息

我可以在每次收到websocket请求时创建一个新连接。但是,我只想创建一次到xmpp服务器的连接,并将接收到的任何消息发送回相应的websocket

# websock.py
import asyncio
import websockets
from xmpp import connect_client


async def xmpp_connection(websocket, path):
    await connect_client()


start_server = websockets.serve(xmpp_connection, "127.0.0.1", 5678)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
# xmpp.py
import asyncio
import aioxmpp


async def connect_client(local_jid=aioxmpp.JID.fromstr(username), password=password):
    client = aioxmpp.PresenceManagedClient(
        local_jid,
        aioxmpp.make_security_layer(password, no_verify=True)
    )

    def message_received(msg):
        print(msg)

    message_dispatcher = client.summon(
        aioxmpp.dispatcher.SimpleMessageDispatcher
    )
    message_dispatcher.register_callback(
        aioxmpp.MessageType.CHAT,
        None,
        message_received,
    )

    async with client.connected() as stream:
        print('connected')
        while True:
            await asyncio.sleep(1)


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(connect_client())
    loop.close()

Tags: runimportclientloopeventasynciomessageget

热门问题