基于进程内通讯的python聊天室实现方法

本文实例讲述了基于进程内通讯的python聊天室实现方法。分享给大家供大家参考。具体如下:

#!/usr/bin/env python
# added by
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程序设计有所帮助。

Posted in 未分类