import socket
server = socket.socket()
server.bind(('10.7.181.95', 8091))
server.listen(512)
print('开始监听')
while True:
#接收客户端请求
conversation, addr = server.accept()
print('===')
print(addr)
print('++++')
while True:
# 接收消息
message_re = conversation.recv(1024).decode('utf-8')
print(message_re)
print('\\\\\\\\')
# 服务器给客户端发送消息
# 1.服务器给客户端发送一张图片,客户端保存图片到本地
if message_re == '1':
print('\\\\')
with open('files/luffy.jpg', 'rb') as f:
while True:
content = f.read()
if not content:
print('发送完毕')
conversation.send('发送完毕'.encode(encoding='utf-8'))
break
conversation.send(content)
# 关闭连接
# conversation.close()
# 2.服务器输入一段文字发送给客户端, 客户端将文字保存在一个message.txt文件中
elif message_re == '2':
content1 = input('请输入传输文字:')
conversation.send(content1.encode(encoding='utf-8'))
# conversation.close()
# 3.通知服务器关闭连接,并且客户端结束
elif message_re == '3':
conversation.close()
print('断开连接')
break
import socket
client = socket.socket()
client.connect(('10.7.181.95', 8091))
while True:
# 给服务器发送消息
message = input('请输入你想要的序号:')
client.send(message.encode(encoding='utf-8'))
if message == '1':
data = bytes()
re_data = client.recv(1024)
while re_data:
data += re_data
re_data = client.recv(1024)
if re_data == '发送完毕'.encode(encoding='utf-8'):
print('接收成功')
break
with open('./files/new_pic.jpg', 'bw') as f:
f.write(data)
print('接收到图片啦')
continue
elif message == '2':
messages = client.recv(1024).decode('utf-8')
with open('./files/message.txt', 'w', encoding='utf-8') as f:
f.write(messages)
print('接收到文档啦')
continue
elif message == '3':
print('中断连接')
break
else:
print('请输入1~3')
continue