基于进程内通讯的python聊天室实现方法
程序员文章站
2023-11-18 17:06:28
本文实例讲述了基于进程内通讯的python聊天室实现方法。分享给大家供大家参考。具体如下:
#!/usr/bin/env python
# Added by &...
本文实例讲述了基于进程内通讯的python聊天室实现方法。分享给大家供大家参考。具体如下:
#!/usr/bin/env python # Added by <ctang@redhat.com> import sys import os from multiprocessing import connection ADDR = ('', 9997) AUTH_KEY = '12345' class Server(object): def __init__(self, username): self.auth_key = AUTH_KEY self.addr = ADDR self.username = username self.listener = connection.Listener(self.addr, authkey=self.auth_key) def listen(self): while True: conn = self.listener.accept() while True: try: request = conn.recv() response = self.response(request) conn.send(response) except EOFError: break conn.close() def reply(self): message = raw_input("%s: " % self.username) return message def output_request(self, request): sys.stdout.write('%s says: %s\n' % request) def response(self, request): self.output_request(request) response = (self.username, self.reply()) return response class Client(object): def __init__(self, username): self.auth_key = AUTH_KEY self.addr = ADDR self.username = username self.display_name = self.make_display_name(username) def make_display_name(self, username): return "%s: " % username def connect(self): self.conn = connection.Client(self.addr, authkey=self.auth_key) while True: message = raw_input(self.display_name) self.send(message) response = self.conn.recv() self.output_response(response) def send(self, message): self.conn.send((self.username, message)) def output_response(self, response): sys.stdout.write('%s says: %s\n' % response) def main(): mode = sys.argv[1] if mode == 'server': username = raw_input("Your name please: ") server = Server(username) server.listen() elif mode == 'client': username = raw_input("Your name please: ") client = Client(username) client.connect() if __name__ == '__main__': main()
希望本文所述对大家的Python程序设计有所帮助。
您可能感兴趣的文章:
- Python 网络编程起步(Socket发送消息)
- Python使用Socket(Https)Post登录百度的实现代码
- python socket网络编程步骤详解(socket套接字使用)
- python实现socket客户端和服务端简单示例
- Python通过websocket与js客户端通信示例分析
- Python采用socket模拟TCP通讯的实现方法
- 初步理解Python进程的信号通讯
- python socket多线程通讯实例分析(聊天室)
- python3.5实现socket通讯示例(TCP)
- python中利用队列asyncio.Queue进行通讯详解
- Python基于socket实现简单的即时通讯功能示例
上一篇: iOS实现短信验证码倒计时