Python3聊天室

服务端(Server)


import socket
import struct
import json
import hashlib
import threading


class Server(object):
    # 频道
    channel = "c485d2ed5cc4ce64fcccca710c7a0bb7"
    # 房间
    room = "fef2576d54dbde017a3a8e4df699ef6d"
    # 编码
    coding = "utf-8"
    # 频道,房间字典
    chat_dic = {channel: {room: {}}}

    def __init__(self):
        # 实例化socket
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 端口重用
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        self.connect()

        self.accept()

    def connect(self):
        self.server.bind(("127.0.0.1", 8080))
        self.server.listen(5)

    def accept(self):
        while True:
            # 监听客户端
            self.conn, self.client_addr = self.server.accept()
            handel_json, data = self.getMassage(self.conn)
            self.chat_dic[self.channel][self.room][self.get_md5(handel_json["user"])] = self.conn
            t = threading.Thread(target=self.massage, name=handel_json["user"], args=(self.conn,))
            t.start()

    def get_md5(self, data):
        return hashlib.md5(data.encode(self.coding)).hexdigest()

    def massage(self, conn):
        while True:
            # 处理报文
            try:
                handel_json, data = self.getMassage(conn)
                users = self.chat_dic[self.channel][self.room]
                for index, item in users.items():
                    user = self.get_md5(handel_json["user"])
                    if index != user and item != "":
                        self.setMassgae(item, handel_json["user"], data)
            finally:
                print("***************************************")

    def getMassage(self, conn):
        res = conn.recv(4)
        handel_len = struct.unpack('i', res)[0]
        res_data = conn.recv(handel_len)
        handel_json = json.loads(res_data.decode(self.coding))
        data = conn.recv(handel_json["len"]).decode(self.coding)

        return handel_json, data

    def setMassgae(self, conn, user, data, channel="channel", room="room"):
        handle_json = {
            "channel": channel,
            "room": room,
            "user": user,
            "len": len(data.encode(self.coding))
        }
        handle = json.dumps(handle_json)
        handel_len = struct.pack('i', len(handle))
        conn.sendall(handel_len)
        conn.sendall(handle.encode("utf-8"))
        conn.sendall(data.encode("utf-8"))


if __name__ == "__main__":
    Server()

客户端(Client)


import json
import socket
import struct
from threading import Thread, currentThread


class MyClient(object):
    # 字符集编码
    coding = 'utf-8'

    def __init__(self):
        self.phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.res = self.phone.connect(("127.0.0.1", 8080))
        t = Thread(target=self.read)
        t.start()

    def read(self):
        while True:
            handel_json, data = self.getMassage(self.phone)
            print(data)

    def write(self):
        while True:
            nick = input("name >>>:").strip()
            if nick:
                self.setMassgae(self.phone, nick, nick)
                break

        while True:
            msg = input(nick + " >>>:").strip()
            if not msg: continue
            self.setMassgae(self.phone, nick, msg)

    def close(self):
        self.phone.close()

    def getMassage(self, conn):
        res = conn.recv(4)
        handel_len = struct.unpack('i', res)[0]
        res_data = conn.recv(handel_len)
        handel_json = json.loads(res_data.decode(self.coding))
        data = conn.recv(handel_json["len"]).decode(self.coding)

        return handel_json, data

    def setMassgae(self, conn, user, data, channel="channel", room="room"):
        handle_json = {
            "channel": channel,
            "room": room,
            "user": user,
            "len": len(data.encode(self.coding))
        }
        handle = json.dumps(handle_json)
        handel_len = struct.pack('i', len(handle))
        conn.sendall(handel_len)
        conn.sendall(handle.encode("utf-8"))
        conn.sendall(data.encode("utf-8"))


if __name__ == "__main__":
    a = MyClient()
    a.write()

你可能感兴趣的:(python)