基于进程内通讯的python聊天室实现方法
作者:不吃皮蛋 时间:2021-01-24 03:50:53
本文实例讲述了基于进程内通讯的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,聊天室
0
投稿
猜你喜欢
Python中的字典及其使用方法
2022-03-22 13:31:49
网站有效设计的10个原则
2008-02-11 17:12:00
CASE表达式实现基于条件逻辑来返回一个值
2024-01-19 23:18:45
python matplotlib自定义colorbar颜色条及内置色条详解
2023-04-03 16:50:34
js断点调试心得分享(必看篇)
2023-07-06 22:13:25
读写json中文ASCII乱码问题的解决方法
2023-02-13 02:32:25
教程:mysql申明变量以及赋值
2009-10-26 10:31:00
Python网络编程基于多线程实现多用户全双工聊天功能示例
2021-01-30 06:29:37
Python如何生成随机数及random随机数模块应用
2022-07-28 22:24:21
详细讲解HTTP协议工作方式
2022-01-08 11:55:59
mysql binlog二进制日志详解
2024-01-19 09:09:56
跟老齐学Python之私有函数和专有方法
2021-04-13 20:38:18
Pygame与OpenCV联合播放视频并保证音画同步
2021-09-04 22:23:11
玩转python爬虫之URLError异常处理
2021-03-22 07:36:34
Go语言基础学习教程
2024-02-06 07:12:11
解决Keras 中加入lambda层无法正常载入模型问题
2022-02-21 03:41:11
sql server如何去除数据中的一些无用的空格
2024-01-18 02:22:22
python实现文件助手中查看微信撤回消息
2023-09-03 07:23:50
显示/隐藏引出的CSS Bug
2010-10-20 20:13:00
asp生成UTF-8格式的文件方法
2008-01-26 20:59:00