Server.py文件
import os
import socket
server = socket.socket()
server.bind(('10.7.181.132', 8890))
server.listen(200)
print('开始监听......')
connect, address = server.accept()
while True:
send_message = 'a.请求文字信息\nb.请求图片信息'
connect.send(send_message.encode())
answer1 = connect.recv(1024).decode(encoding='utf-8')
if answer1 == 'a':
print('您可以开始和客户端进行沟通了')
while True:
chat_client = connect.recv(1024).decode(encoding='utf-8')
print(chat_client)
message = input('服务端:').encode()
connect.send(message)
print('\r\n')
if chat_client == 'bye' or chat_client == '再见':
break
elif answer1 == 'b':
print('为客户提供图片信息')
list1 = os.listdir('files')
choices2 = str(list1)
connect.send(choices2.encode())
answer2 = connect.recv(2048).decode(encoding='utf-8')
with open('files/' + answer2, 'rb') as f:
connect.send(f.read())
else:
print('选项不正确,关闭...')
connect.close()
break
files文件夹供Server使用
Client.py文件
import socket
client = socket.socket()
client.connect(('10.7.181.132', 8890))
choices1 = client.recv(1024)
while True:
print(choices1.decode(encoding='utf-8'))
answer1 = input('请选择:')
client.send(answer1.encode())
if answer1 == 'a':
print('现在您可以开始和服务器进行沟通了')
while True:
message = input('客户端:')
client.send(message.encode())
print('发送成功...')
chat_server = client.recv(1024).decode(encoding='utf-8')
print('服务端:', chat_server)
print('\r\n')
if message == 'bye' or message == '再见':
break
elif answer1 == 'b':
list1 = eval(client.recv(2048).decode(encoding='utf-8'))
while True:
print(list1)
answer2 = input('请输入你想要的图片的名字:')
if answer2 in list1:
client.send(answer2.encode())
load_path = 'files2/' + answer2
while True:
recv_photo = client.recv(1024)
# print(len(recv_photo))
with open(load_path, 'ab') as f:
f.write(recv_photo)
if len(recv_photo) < 1024:
print('图片下载完成')
break
break
else:
print('输入错误,请重新选择')
else:
print('没有该选项,退出程序')
client.close()
break
files2文件夹供Client使用