服务器:
"""______lxh______"""
from socket import *
from threading import Thread
import os
class ImgDownload(Thread):
def __init__(self, connect, address):
super().__init__()
self.connect = connect
self.address = address
def run(self) -> None:
# 循环操作
while True:
re_ask = str(self.connect.recv(1024), encoding='utf-8') # 获取请求
if re_ask == 'a':
while True:
# self.connect.send(input('输入:').encode())
rec = self.connect.recv(1024).decode()
if rec == 'exit':
break
else:
print(self.address, rec)
elif re_ask == 'b':
dirs = os.listdir('files') # 获取文件目录列表
str_dirs = str(dirs) + '\n请输入你想要的图片的名字:'
self.connect.send(str_dirs.encode()) # 发送文件目录以及提示输入
re_name = str(self.connect.recv(1024), encoding='utf-8') # 接收客户端输入信息
path = 'files/' + re_name # 合成路径
if os.path.exists(path): # 对存在的文件进行操作
self.connect.send('图片存在!'.encode())
with open(path, 'rb') as f:
self.connect.send(f.read())
else:
self.connect.send('图片不存在!'.encode())
elif re_ask == 'exit':
print(self.address, '退出连接')
break
def main():
server = socket() # 创建套接字对象
server.bind(('10.7.181.115', 9926)) # 绑定ip和端口
server.listen(628)
while True: # 让程序一直运行
connect, address = server.accept() # 接收请求建立连接
print(connect, address) # 服务端打印请求信息
ImgDownload(connect, address).start() # 启动线程
if __name__ == '__main__':
main()
客户端:
"""______lxh______"""
from socket import *
client = socket() # 创建套接字对象
client.connect(('10.7.181.115', 9926)) # 连接ip和端口
path = 'im_client/' # 文件存放路径
while True:
print('a.请求文字信息\nb.请求图片信息\n(输入exit退出)')
ask = input('输入:')
client.send(ask.encode()) # 返回选项请求
if ask == 'a':
while True:
# print('接收:%s' % client.recv(1024).decode()) # 打印文本信息
user_in = input('输入exit退出\n输入:')
if user_in == 'exit':
break
else:
client.send(user_in.encode())
elif ask == 'b':
print(client.recv(1024).decode())
im_name = input('输入图片名字:')
client.send(im_name.encode())
re_ask = client.recv(1024).decode() # 接收文件是否存在
print(re_ask)
if re_ask != '图片不存在!':
while True:
re_img = client.recv(1024)
with open(path + im_name, 'ab') as f:
f.write(re_img)
if len(re_img) < 1024:
print('接收成功!')
break
elif ask == 'exit':
break