python通过进程内通信实现的聊天室程序代码

2022-03-11 00:00:00 进程 聊天室 程序代码

python通过进程内通信实现的聊天室程序代码,一个程序包含了服务端和客户端,使用server和client参数运行不同的端实现聊天功能。

"""
作者:皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/23
功能描述:python通过进程内通信实现的聊天室程序代码
运行方式:
服务端: python chat.py server
客户端: python chat.py client
"""

import sys
import os
from multiprocessing import connection

ADDR = ('', 9997)
AUTH_KEY = b'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 = 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 = 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 = input("Your name please: ")
        server = Server(username)
        server.listen()
    elif mode == 'client':
        username = input("Your name please: ")
        client = Client(username)
        client.connect()


if __name__ == '__main__':
    main()

运行方式:
服务端: python chat.py server
客户端: python chat.py client

运行完成后就可以在两个终端进行聊天了。

以上代码在python3.9环境测试通过

相关文章