程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

Asyncio server and client

发布于2025-01-05 09:13     阅读(730)     评论(0)     点赞(3)     收藏(0)


Here is a demo implements the communication between client and server.

import asyncio
import json
import time

reader = None
writer = None
ip = '127.0.0.1'
port = 8889


async def handle_input():
    while True:
      user_input = input("[You]: ")
      await send_message(user_input)

async def send_message(message):
    if not reader or not writer:
        print("[Error]: Not connected to the message server.")
        return

    try:
        message_data = {
            "sender": "name",
            "message": message
        }
        request_data = json.dumps(message_data)
        writer.write(request_data.encode('utf-8'))
        await writer.drain()
        
        print(f"[Info]: Message sent: {message}")

    except Exception as e:
        print(f"[Error]: Failed to send message. Error: {e}")

async def message_test():
    
    global reader, writer
    try:
       
        reader, writer = await asyncio.open_connection(ip, port)
        print(f"[Info]: Connected to the conference message server")

        await handle_input()

    except Exception as e:
        print(f"[Error]: Failed to start the conference client. Error: {e}")


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

Above is the client code

import asyncio
import json

clients = []


async def handle_client(reader, writer):

    
    addr = writer.get_extra_info('peername')
    print(f"[Info]: New connection from {addr}")

 
    clients.append((reader, writer))

    try:
        while True:
            data = await reader.read(100)
            if not data:
                break  
            message = data.decode('utf-8')
            print(f"[Info]: Received message: {message}")


    except asyncio.CancelledError:
        pass
    finally:
        
        clients.remove((reader, writer))
        print(f"[Info]: Connection closed by {addr}")
        writer.close()
        await writer.wait_closed()

async def start_server():
    server = await asyncio.start_server(
        handle_client, '127.0.0.1', 8889
    )
    addr = server.sockets[0].getsockname()
    print(f"[Info]: Server started on {addr}")

    async with server:
        await server.serve_forever()

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

Above is the server code.

When the program starts running,the client receives the user message from the input and sends it to the server.The first time entering the while loop, the server receives the message successfully.The second time and the next few times, the client is able to print "[Info]: Message sent: {message}", but the server did not receive the message.

I wonder why this happens

I tried to change the while loop to

user_input = input("[You]: ")
await send_message(user_input)

user_input = input("[You]: ")
await send_message(user_input)

Then server successfully receives the message both times.

client

server

Here's a screenshot of me running the program.The client sends multiple messages, but the server receives only the first one.

my python version==3.12.4


解决方案


暂无回答



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/2046779/5ebbf91e9d9a9a9f2241/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

3 0
收藏该文
已收藏

评论内容:(最多支持255个字符)