• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

一个使用进程内通讯的python聊天室代码

python 水墨上仙 2004次浏览

一个使用进程内通讯的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聊天室代码
喜欢 (0)
加载中……