Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python WebSocket不断关闭连接_Python_Api_Websocket - Fatal编程技术网

使用Python WebSocket不断关闭连接

使用Python WebSocket不断关闭连接,python,api,websocket,Python,Api,Websocket,我试着设置一个WebSocket服务器和一个API来通过浏览器访问它 我刚接触Python一周,我希望这有点道理 我有一个服务器类 **Server.py** # WS server that sends messages at random intervals import asyncio import datetime import random import websockets async def time(websocket, path): while True:

我试着设置一个WebSocket服务器和一个API来通过浏览器访问它

我刚接触Python一周,我希望这有点道理

我有一个服务器类

**Server.py**
# WS server that sends messages at random intervals
import asyncio
import datetime
import random
import websockets

async def time(websocket, path):
    while True:
        now = datetime.datetime.utcnow().isoformat() + "Z"
        await websocket.send(now)
        await asyncio.sleep(random.random() * 3)


async def echo(websocket, path):
    async for message in websocket:
        await websocket.send(message)


async def router(websocket, path):
    if path == "/get":
        await time(websocket)
    elif path == "/post":
        await echo(websocket)

asyncio.get_event_loop().run_until_complete(
    websockets.serve(router, "127.0.0.1", 8081, ping_interval=None))

asyncio.get_event_loop().run_forever()
和一个API类

**API.py**
from quart import Quart
import json
import websockets

app = Quart(__name__)

@app.route('/get',methods=['GET'])
async def foo1():
    uri = "ws://localhost:8081"
    async with websockets.connect(uri) as websocket:
        try:
            receivedMessage = await websocket.recv()
            print(f"< {receivedMessage}")
        except:
            print('Reconnecting')
            websocket = await websockets.connect(uri)

    return ' '

@app.route('/post', methods=['POST'])
async def foo2():
    uri = "ws://localhost:8081"
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello world!")
        try:
            await websocket.recv()
        except:
            print('Reconnecting')
            websocket = await websockets.connect(uri)
 
if __name__ == '__main__':
   app.run()
**API.py**
从夸脱进口夸脱
导入json
导入WebSocket
app=夸脱(\uuuuuu名称\uuuuuuuuu)
@app.route('/get',methods=['get'])
异步def foo1():
uri=“ws://localhost:8081”
与websocket异步。作为websocket连接(uri):
尝试:
receivedMessage=wait websocket.recv()
打印(f“<{receivedMessage}”)
除:
打印('重新连接')
websocket=等待websocket.connect(uri)
返回“”
@app.route('/post',methods=['post'])
异步def foo2():
uri=“ws://localhost:8081”
与websocket异步。作为websocket连接(uri):
等待websocket。发送(“你好,世界!”)
尝试:
等待websocket.recv()
除:
打印('重新连接')
websocket=等待websocket.connect(uri)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
app.run()
我的目标是能够根据正在访问的API路径从服务器访问不同的函数(见此处:)

我遇到的问题是,“重新连接”经常出现,而当我使用/get或/post时,实际上什么也没有发生(即,它似乎在.recv()发生后关闭-我知道这一点,因为我在前面看到了ConnectionClosedOk-没有任何原因)

我真的不明白我现在在做什么,哈哈,这很让人困惑。当服务器只有一个函数时,我确实让事情开始工作了(不断地吐出时间戳),而API只有一个get函数(显示请求的当前时间)…在我实现了路由器功能之后,现在一切都不正常了。

我的Python知识非常有限,所以尽可能详细的回答对我来说真的很有帮助

我假设POST方法会在服务器的控制台上显示“Hello world!”,但我可能错了:(我刚刚在一些教程文档中看到过它


编辑:另外,我无法访问localhost:(port)/post;它说指定的方法对此资源无效;这是为什么?

我帮不了你,但你能指出你正在使用的Python版本吗?我帮不了你,但你能指出你正在使用的Python版本吗。