欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

pythonsocket通信协程实现多人聊天室

时间:2023-06-24

在服务端,使用python官方的asyncio模块,利用asyncio.start_server方法生成服务器,对每个连接采取分而治之的思路,用协程方法同时进行多个连接。
客户端采用多线程,用两个线程分别运行接收机和发信机。

服务端

#server.pyimport asyncio# 连接表coonlist = []# 广播机async def boarder(message: str, coonlist=coonlist): for writer in coonlist: date = message.encode('utf-8') # 信息编码 writer.write(date)# 定义服务器的事件处理async def handle_echo(reader, writer): coonlist.append(writer) # 保存发信机队列 while True: data = await reader.read(100) if len(data) < 1: break # 收到空数据即关闭连接 message = data.decode('utf-8') addr = writer.get_extra_info('peername') print(f"Received {message!r} from {addr!r}") await boarder(message)#广播消息 print("Close the connection") writer.close() coonlist.remove(writer)async def main(): server = await asyncio.start_server( handle_echo, '127.0.0.1', 10000) addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets) print(f'Serving on {addrs}') async with server: await server.serve_forever()asyncio.run(main())

客户端

# -*- coding: UTF-8 -*-import threadingimport socket# 客户端 发送一个数据,再接收一个数据import timeclass Client: SERVER_IP='localhost' PORT=10000 def __init__(self,serve_ip=SERVER_IP,port=PORT): self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 声明socket类型,同时生成链接对象 self.client.connect((serve_ip, port)) # 建立一个链接,连接到服务器端口 def __del__(self): self.client.close() def close(self): self.client.close() def __sender(self): while True: time.sleep(0.1) msg = input("n发送的信息:") self.client.send(msg.encode('utf-8')) def __receiver(self): while True: data = self.client.recv(1024) if not data: print("n没有消息。") break msg = data.decode('utf-8') print("n收到的信息:", msg) def loop(self): receiver=threading.Thread(target=self.__receiver) receiver.start() sender=threading.Thread(target=self.__sender) sender.start()c=Client()c.loop()

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。