天下程序员首页cx06.com
管理 |  登录 |  注册
袁鹏飞的小屋
笔记(共39个) > python

异步websockets服务端和客户端

阅读 0赞 0回复 2024-10-09 10:03:26
import asyncio
import websockets

async def receive_message(websocket):
    async for message in websocket:
        print(f"Received: {message}")

async def send_message(websocket):
    while True:
        message = "Server message"
        await websocket.send(message)
        await asyncio.sleep(5)

async def handle_connection(websocket, path):
    print(f"Client connected.")
    receive_task = asyncio.create_task(receive_message(websocket))
    send_task = asyncio.create_task(send_message(websocket))
    await asyncio.gather(receive_task, send_task)

async def start_server():
    server = await websockets.serve(handle_connection, 'localhost', 8888)
    print(f"Server started on port 8888.")
    await server.wait_closed()

if __name__ == "__main__":
    asyncio.run(start_server())


    import asyncio
import websockets

connected_clients = set()

async def receive_message(websocket):
    async for message in websocket:
        print(f"Received: {message}")

async def send_message(websocket):
    while True:
        message = "Server message"
        await websocket.send(message)
        await asyncio.sleep(5)

async def disconnect_server(websocket):
    connected_clients.remove(websocket)
    await websocket.close()
    print("Client disconnected.")

async def handle_connection(websocket, path):
    print(f"Client connected.")
    connected_clients.add(websocket)
    receive_task = asyncio.create_task(receive_message(websocket))
    send_task = asyncio.create_task(send_message(websocket))
    try:
        await asyncio.gather(receive_task, send_task)
    except websockets.exceptions.ConnectionClosedError:
        await disconnect_server(websocket)

async def start_server():
    server = await websockets.serve(handle_connection, 'localhost', 8888)
    print(f"Server started on port 8888.")
    await server.wait_closed()

if __name__ == "__main__":
    asyncio.run(start_server())


import asyncio
import websockets

async def receive_message(websocket):
    async for message in websocket:
        print(f"Received from server: {message}")

async def send_message(websocket):
    while True:
        message = input("Enter a message to send: ")
        await websocket.send(message)

async def connect_to_server():
    async with websockets.connect('ws://localhost:8888') as websocket:
        print("Connected to server.")
        receive_task = asyncio.create_task(receive_message(websocket))
        send_task = asyncio.create_task(send_message(websocket))
        await asyncio.gather(receive_task, send_task)

if __name__ == "__main__":
    asyncio.run(connect_to_server())

赞(0)

文章作者置顶的回复

全部回复列表 当前第(1)页

添加回复,文明发言,会审核.(服务区回复可以发广告)

作者最新笔记
天下程序员 www.cx06.com 程序员的网上家园!
作者微信:13126507001