发布于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.
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黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!