Python Websockets:在等待传入消息的同时发送消息

时间:2018-12-05 07:47:36

标签: python python-3.x websocket python-asyncio

我正在尝试每秒通过websocket将位置更新发送到服务器,同时等待来自服务器的消息。为此,我将Python与Websockets和asyncio一起使用。

这是我的代码:

#!/usr/bin/env python

import argparse
import sys
import time
import asyncio
import websockets

parser = argparse.ArgumentParser()

parser.add_argument('--host', help='The host to which the socket should bind', required=True)
parser.add_argument('--port', help='The port to which the socket should bind', required=True)
parser.add_argument('--file', help='Path to the coordinate resource file. The file should have the following structure: latitude,longitude,elevation,speed;latitude,longitude,...', required=True)
args = parser.parse_args()

with open(args.file, 'r') as file:
    locationsStr = file.read()
    if locationsStr.endswith(';'):
        locationsStr = locationsStr[:-1]
locations = locationsStr.split(';')
msg = []
for l in locations:
    tmp = l.split(',')
    msg.append(tmp)

def getMsg(i):
    message = '{\"type\" : \"PositionUpdate\",\"position\": {\"latitude\": ' + msg[i][0] +',\"longitude\": ' + msg[i][1] + ',\"elevation\": ' + msg[i][2] + ',\"speed\": ' + msg[i][3] + '}}'
    return message

async def sendPos(ws):
    i = 0
    while True:
        m = getMsg(i)
        print("Sending position {}".format(i))
        await ws.send(m)
        i += 1
        if i >= len(msg):
            i = 0
        time.sleep(1)

async def recvMsg(ws):
    while True:
        msg = await ws.recv()
        print(msg)

async def main():
    async with websockets.connect('ws://' + args.host + ':' + args.port) as ws:
        t1 = asyncio.create_task(recvMsg(ws))
        t2 = asyncio.create_task(sendPos(ws))
        await t1
        await t2

asyncio.get_event_loop().run_until_complete(main())

这会连接到服务器并每秒发送一条消息,但不会接收服务器发送的消息。

0 个答案:

没有答案