简体   繁体   中英

Python Websocket only receives once from client

I want to send values from a for loop from the client-server but the server only receives the first value and the connection is cut shortly

Client

import asyncio
import websockets
import time

async def message():
    async with websockets.connect("ws://-------:5051") as socket:

        for i in range(20):
            await socket.send(f"{i}")
            print(i)
            time.sleep(4)

asyncio.get_event_loop().run_until_complete(message()) 

Server

import asyncio
import websockets


async def consumer_handler(websocket,path):
        client_type = await websocket.recv()
        print(client_type)



start_server = websockets.serve(consumer_handler,"ws://-------:5051", 5051)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()


So, your consumer_handler receives message once and finishes.
You need to add loop.
Try something like this:

async def consumer_handler(websocket, path):
    async for msg in websocket:
        print(msg)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM