我正在编写一个应用程序,它将以用户身份连接到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()
目前没有回答
相关问题 更多 >
编程相关推荐