day19-多线程实现socket编程

服务端.py

from socket import *
from fileManager import*
from threading import*


class ServerThread(Thread):
    """创建子线程"""
    def __init__(self, connection, address):
        super().__init__()
        self.connection = connection
        self.address = address

    def run(self):
        picture_nums = Number()
        # 让通信一直进行
        while True:
            # 接收信息
            re_message = self.connection.recv(1024).decode(encoding='utf-8')
            if re_message == '1':
                # print('发送文字')
                message = input('请输入:')
                self.connection.send(message.encode())
                print('文字发送成功!')
            elif re_message == '2':
                # 发送图片
                picture_message = binary_read('./server_files./图片.jpg')
                self.connection.send(picture_message)
                print('图片发送成功!')
            elif re_message == '3':
                # 发送视频
                video_message = binary_read('./server_files/视频.mp4')
                self.connection.send(video_message)
                print('视频发送成功!')
            elif re_message == '4':
                # 接收图片
                picture_data = bytes()
                while True:
                    picture_message = self.connection.recv(1024)
                    if len(picture_message) < 1024:
                        picture_data += picture_message
                        binary_write('./server_files/图片%d.jpg' % picture_nums.create_num(), picture_data)
                        break
                    picture_data += picture_message
                print('图片接收成功!')
            elif re_message == '5':
                self.connection.close()
                print('%s已离开...' % self.address[0])
                break
            else:
                continue


def create_server():
    server = socket()
    server.bind(('10.7.160.92', 1234))
    server.listen(512)
    print('开始监听...')
    while True:
        connection, address = server.accept()
        print('欢迎%s...' % address[0])
        t1 = ServerThread(connection, address)
        t1.start()


if __name__ == '__main__':
    create_server()

客户端.py

from socket import *
from fileManager import *


def clients():
    client = socket()
    client.connect(('10.7.160.92', 1234))
    text_nums = Number()
    picture_nums = Number()
    video_nums = Number()
    while True:
        print('1.接收文字 2.接收图片 3.接收视频 4.发送图片 5.退出')
        message = input('请选择:')
        client.send(message.encode())
        if message == '1':
            # 接收文字
            all_message = client.recv(1024).decode(encoding='utf-8')
            text_write('./client_files/聊天记录%d.txt' % text_nums.create_num(), all_message)
            print('文字接收成功!')
        elif message == '2':
            # 接收图片
            picture_data = bytes()
            while True:
                picture_message = client.recv(1024)
                if len(picture_message) < 1024:
                    picture_data += picture_message
                    binary_write('./client_files/图片%d.jpg' % picture_nums.create_num(), picture_data)
                    print('图片接收成功!')
                    break
                picture_data += picture_message
        elif message == '3':
            # 接收视频
            all_data = bytes()
            while True:
                data1 = client.recv(1024)
                if len(data1) < 1024:
                    all_data += data1
                    all_data = binary_write('./client_files/视频%d.mp4' % video_nums.create_num(), all_data)
                    print('视频接收成功!')
                    break
                all_data += data1
        elif message == '4':
            # 发送图片
            picture_message = binary_read('./server_files./图片.jpg')
            client.send(picture_message)
            print('图片发送成功!')
        elif message == '5':
            break
        else:
            print('输入错误!')


if __name__ == '__main__':
    clients()

fileManager.py

class Number:
    """产生序号"""
    def __init__(self):
        self._nums = 0

    @property
    def nums(self):
        return self._nums

    def create_num(self):
        self._nums += 1
        return self._nums


def text_write(file_path: str, all_message: str):
    """
    写入文本文件
    :param file_path:
    :return: None
    """
    if not all_message:
        return
    with open(file_path, 'a', encoding='utf-8') as f:
        f.write(all_message+'\n')


def binary_read(file_path: str):
    """
    获得二进制文件
    :param file_path:
    :return:
    """
    try:
        with open(file_path, 'rb') as f:
            return f.read()
    except:
        return None


def binary_write(file_path: str, all_message: bytes):
    """
    写入二进制文件
    :param file_path:
    :param all_message:
    :return:
    """
    if not all_message:
        return
    with open(file_path, 'wb') as f:
        f.write(all_message)

你可能感兴趣的:(day19-多线程实现socket编程)