Python 自定义websocket客户端以获取数据输入并转发它
我在这里找到了我非常喜欢的示例代码: 然而,我想对它进行一点定制,这样它就可以从我自己那里获取一些输入,然后转发消息,但是由于这个异步等待的事情,我没有成功地完成它,这有点令人尴尬。。因此,我请求帮助 类别代码与链接中的相同:Python 自定义websocket客户端以获取数据输入并转发它,python,websocket,python-asyncio,Python,Websocket,Python Asyncio,我在这里找到了我非常喜欢的示例代码: 然而,我想对它进行一点定制,这样它就可以从我自己那里获取一些输入,然后转发消息,但是由于这个异步等待的事情,我没有成功地完成它,这有点令人尴尬。。因此,我请求帮助 类别代码与链接中的相同: import websockets import asyncio class WebSocketClient(): def __init__(self): pass async def connect(self):
import websockets
import asyncio
class WebSocketClient():
def __init__(self):
pass
async def connect(self):
self.connection = await websockets.client.connect('ws://ip-adress:5080/ws/testchannel')
if self.connection.open:
print('Connection stablished. Client correcly connected')
await self.sendMessage('Hey server, i am acting as a WS client for my MQTT client! :)')
return self.connection
async def receive_data_into_client(self, yoo):
print(yoo)
forward_message = await self.sendMessage(yoo)
return forward_message
async def sendMessage(self, message):
await self.connection.send(message)
async def receiveMessage(self, connection):
while True:
try:
message = await connection.recv()
print('Received message from server: ' + str(message))
except websockets.exceptions.ConnectionClosed:
print('Connection with server closed')
break
async def ping_pong(self, connection):
while True:
try:
await connection.send('ping')
await asyncio.sleep(5)
except websockets.exceptions.ConnectionClosed:
print('Connection with server closed')
break
这是我的main.py,我将行“ifname='main':”与函数切换为:
def run_connection():
client = WebSocketClient()
client.receive_data_into_client("this came in, right?")
loop = asyncio.get_event_loop()
connection = loop.run_until_complete(client.connect())
tasks = [
asyncio.ensure_future(client.ping_pong(connection)),
asyncio.ensure_future(client.receiveMessage(connection)),
]
loop.run_until_complete(asyncio.wait(tasks))
run_connection()
我希望能够在转发消息之前键入消息并将其放入类中,因为我还计划稍后将其与MQTT代理集成
有人能帮我弄一下这个零件吗