2019-08-14

作业

服务器端

"""author = TK林"""

import socket
import os

# 创建套接字对象,设置ip地址和通讯协议类型

server = socket.socket()

# 绑定ip和端口
# server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # 端口重复

server.bind(('10.7.181.112', 9999))

# 等待连接并设置同一时间连接的最大数量

server.listen(500)

while True:

    connect, address = server.accept()  # 接收信息

    while True:
        # 接收客户端发送的message
        recv_message = connect.recv(1024)
        message = recv_message.decode(encoding='utf-8')
        print(message)
        if message == 'a':
            message_s = input("请输入:")  # 服务器输入信息
            connect.send(message_s.encode())  # 发送服务器输入的信息
        elif message == 'b':
            list_s = os.listdir(path='photo-set')
            # print(list_s)
            connect.send(str(list_s).encode())
            recv_name = connect.recv(1024)
            name = recv_name.decode(encoding='utf-8')  # 接收图片的名字
            # print(name)
            # print(type(name))
            for x in list_s:
                # print(type(x), x)
                if name == x:

                    # print("hello")
                    with open('photo-set/{}'.format(name), 'rb') as f:
                        # print(f.read())
                        connect.send(f.read())
                else:
                    print("名字输入错误")
                    break

                # connect.close()   # 关闭

客户端

"""author = TK林"""

import socket
import json

client = socket.socket()

# c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # 端口重复

client.connect(('10.7.181.112', 9999))

while True:
    print("a.请求文字信息\nb.请求图片信息")
    char = input("请选择a or b:")

    if char == 'a':
        client.send(char.encode())  # 发送消息
        re_data = client.recv(1024)  # 接收消息
        print(re_data.decode(encoding='utf-8'))
    elif char == 'b':
        while True:   # 接收图片信息
            client.send(char.encode())  # 发送消息
            re_data = client.recv(1024)
            re_list =re_data.decode(encoding='utf-8')  # 将接收的json数据转换为python数据
            # print(re_list)
            photo_name = input("请输入你想要的图片名字:")
            client.send(photo_name.encode())    # 向服务器发送想要的图片的名字
            # print(type(photo_name))
            while True:   # 接收图片
                re_photo = client.recv(1024)
                with open("photo-get/{}".format(photo_name), 'ab') as f:
                    # re_photo = client.recv(1024)
                    f.write(re_photo)

                if len(re_photo) < 1024:
                    break
    else:
        print("输入错误")

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