服务器
import socket
#服务器
sever = socket.socket()
sever.bind(('10.7.156.57',8888))
sever.listen(512)
print('开始监听')
while True:
conversation,addr = sever.accept()
print('正在会话中')
while True:
# 接收消息
message_re = conversation.recv(1024).decode('utf-8')
print('客户端(%s): %s' % (addr[0][-2:], message_re))
if message_re == '1':
print('对方需要图片,正在发送')
with open('./aa.jpg', 'br') as f:
content = f.read()
conversation.send(content)
conversation.close()
print('已发送')
if message_re == '2':
print('对方需要文字')
content = '这是一段文字请保存'
print('已发送')
conversation.send(content.encode('utf-8'))
if message_re == '3':
print('对方终止了会话')
break
客户端
#客户端
import socket
client = socket.socket()
client.connect(('10.7.156.57',8888))
data = bytes()
while True:
# message_re = conversation.recv(1024).decode('utf-8')
# print('客户端(%s): %s' % (addr[0][-2:],message_re))
print('===============\n1.需要图片\n2.需要文字\n3.通知结束\n===============')
instruction = input('请选择操作:')
if instruction == '1':
message = '1'
client.send(message.encode('utf-8'))
print('已选择需要图片')
message_re = client.recv(1024)
data += message_re # 将每次获取到的数据叠加
# print('接收到数据')
message_re = client.recv(1024)
with open('./new.jpg', 'bw') as f:
f.write(data)
print('接收完成')
elif instruction == '2':
message = '2'
client.send(message.encode('utf-8'))
print('已选择需要文字')
re_data = client.recv(1024)
print('服务器:', re_data.decode('utf-8'))
elif instruction == '3':
message = '3'
client.send(message.encode('utf-8'))
print('通知结束')
# break
else:
print('错误指令')
网友评论