一、server
#!/user/bin/env python
# -*- coding:utf-8 -*-
import os
from socket import *
import threading
server = socket()
server.bind(('10.7.181.120', 1029))
server.listen(100)
class ThreadOpj(threading.Thread):
def __init__(self, connect: socket, address: socket):
super().__init__()
self.connect = connect
self.address = address
def run(self):
while True:
recv_data = self.connect.recv(1024).decode()
print('{}请求消息:{}'.format(self.address, recv_data))
if recv_data == 'a':
while True:
self.connect.send('请求通过'.encode())
while True:
text_recv5 = self.connect.recv(1024).decode()
print('{}:{}'.format(self.address, text_recv5))
if text_recv5 != 'exit':
self.connect.send(input('服务器to{}:'.format(self.address)).encode())
else:
break
if text_recv5 == 'exit':
break
elif recv_data == 'b':
list1 = os.listdir('picture\\')
self.connect.send(str(list1).encode())
while True:
file_name_num = self.connect.recv(1024).decode()
if file_name_num != 'exit':
file_name_num = int(file_name_num)
for i in range(len(list1)):
if file_name_num == i + 1:
with open('picture\\' + list1[i], 'rb') as f:
print('服务器正在向{}发送文件{}'.format(self.address, list1[i]))
self.connect.send(f.read())
print('文件发送完成!!!!to:{}'.format(self.address))
else:
break
def start_server():
while True:
connect, address = server.accept()
client1 = ThreadOpj(connect, address)
client1.start()
start_server()
二、client
#!/user/bin/env python
# -*- coding:utf-8 -*-
from socket import *
client = socket()
client.connect(('10.7.181.120', 1029))
while True:
print('a.请求文字信息')
print('b.请求图片信息')
print('exit.断开连接')
send_message = input('请选择(a/b/c):')
client.send(send_message.encode())
if send_message == 'a':
while True:
recv_data = client.recv(1024).decode(encoding='utf-8')
print('服务器say:', recv_data)
send_message1 = input('客户端say:')
client.send(send_message1.encode())
if send_message1 == 'exit':
break
elif send_message == 'b':
while True:
recv_data = client.recv(1024).decode(encoding='utf-8')
list1 = eval(recv_data)
while True:
for i in range(len(list1)):
print(i+1, list1[i])
send_message6 = input('请选择要接收的文件:')
if send_message6 != 'exit':
client.send(send_message6.encode())
send_message2 = int(send_message6)
while True:
recv_data = client.recv(1024)
with open('recv_picture\\' + list1[send_message2-1], 'ab') as f:
f.write(recv_data)
if len(recv_data) < 1024:
print('==========成功接收==========')
break
else:
break
if send_message6 == 'exit':
break
elif send_message.encode() == 'exit':
client.close()
print('连接断开')
break