一、server(服务器)
from socket import *
import os
path = 'picture\\'
def file_name(cpath):
return os.listdir(cpath)
server = socket()
server.bind(('127.0.0.1', 1029))
server.listen(10)
while True:
connect, address = server.accept()
while True:
recv_data = connect.recv(1024).decode()
if recv_data == 'a':
connect.send(input('==========服务器:').encode())
elif recv_data == 'b':
list1 = file_name(path) # 返回list1文件名列表
connect.send(str(list1).encode())
recv_data1 = connect.recv(1024).decode()
file1 = list1[int(recv_data1)-1]
with open('.\picture\\' + file1, 'rb') as f:
print('==========正在发送图片:', file1)
connect.send(f.read())
print('==========发送成功==========')
elif recv_data == 'exit':
connect.close()
二、client(客户端)
from socket import *
client = socket()
client.connect(('127.0.0.1', 1029))
while True:
print('a.请求文字信息')
print('b.请求图片信息')
print('c.断开连接')
send_message = input('请选择(a/b/c):')
client.send(send_message.encode())
if send_message == 'a':
recv_data = client.recv(1024).decode(encoding='utf-8')
print('服务器:', recv_data)
elif send_message == 'b':
recv_data = client.recv(1024).decode(encoding='utf-8')
list1 = eval(recv_data)
# print(list1)
for i in range(len(list1)):
print(i+1, list1[i])
send_message1 = input('请选择:')
client.send(send_message1.encode())
send_message2 = int(send_message1)
while True:
recv_data = client.recv(1024)
with open('picture1\\' + list1[send_message2-1], 'ab') as f:
f.write(recv_data)
if len(recv_data) < 1024:
print('==========成功接收==========')
break
elif send_message.encode() == 'c':
client.close()
print('连接断开')
break