HW8-14

HW

814hw.png

Server

import socket
import os

mx_server = socket.socket()
mx_server.bind(('10.7.181.113', 8088))
mx_server.listen(20)
connect, address = mx_server.accept()

while True:
    send_message = 'a.请求文字消息/n b.请求图片消息:'
    connect.send(send_message.encode())
    ans1 = connect.recv(2048).decode(encoding='utf-8')
    if ans1 == 'a':
        print('Connection establishment')
        while True:
            chat_msg = connect.recv(2048)
            print('Received', str(chat_msg, encoding='utf-8'))
            send_msg = input('Server:')
            connect.send(send_msg.encode())
            if chat_msg == '88' or chat_msg == 'bye':
                break
    elif ans1 == 'b':
        print('Image receive mode')
        list1 = os.listdir('files1')
        choice = str(list1)
        connect.send(choice.encode())
        answer2 = connect.recv(2048).decode(encoding='utf-8')
        with open('files1/'+ answer2, 'rb')as f:
            connect.send(f.read())

    else:
        print('Drop out')

        connect.close()

Client

from socket import *

client = socket()
client.connect(('10.7.181.113', 8088))
choice1 = client.recv(2048)

while True:
    print(choice1.decode(encoding='utf-8'))
    ans1 = input('Enter yor choice')
    client.send(ans1.encode())
    if ans1 == 1:
        print('Connection Establishment')
        while True:
            message = input('Server:')
            client.send(message.encode())
            print('Sent succeed!')
            chat_server = client.recv(2048).decode()
            print('Server', chat_server)
            if message == '88' or message == 'bye':
                break
    elif ans1 == 'b':
        list1 = eval(client.recv(2048).decode(encoding='utf-8'))
        while True:
            print(list1)
            ans2 = input('Entering files name which is you want')
            if ans2 in list1:
                client.send(ans2.encode())
                load_path = 'files1/' + ans2
                while True:
                    receive_pg = client.recv(2048)
                    with open(load_path, 'ab')as f:
                        f.write(receive_pg)
                        if len(receive_pg) < 1024:
                            print('Download completed')
                            break
                    break
            else:
                print('Error')
    else:
        client.close()
        print('QUIT')

你可能感兴趣的:(HW8-14)