作业:
1. 客户端和服务器聊天,可以一直聊天,直到一方发送’拜拜’。然后就可以和下一个人一直聊
服务器
import socket
sever = socket.socket()
sever.bind(('10.7.187.123', 9990))
sever.listen(100)
print('开始监听')
while True:
conversation, addr = sever.accept()
while True:
recev_data = conversation.recv(1024)
print('客户端:', recev_data.decode('utf-8'))
if recev_data.decode('utf-8') == '拜拜':
break
send_data = input('服务器:')
conversation.send(send_data.encode('utf-8'))
conversation.close()
客户端
import socket
client = socket.socket()
client.connect(('10.7.187.123', 9990))
while True:
send_data = input('客户端:')
client.send(send_data.encode('utf-8'))
rece_data = client.recv(1024)
if rece_data.decode('utf-8') == '拜拜':
break
print('服务器:', rece_data.decode('utf-8'))
2.客户端给服务器发送请求,请求成功后,客户端给服务发送‘1’,服务器就给客户端发送一张图片;客户端给服务发送‘2’, 服务器就给客户端返回一个json文件中的内容;客户端给服务发送‘3’, 服务器返回’拜拜’,然后断开连接
服务器
import socket
import json
sever = socket.socket()
sever.bind(('10.7.187.123', 9990))
sever.listen(100)
print('开始监听')
while True:
conversation , addr = sever.accept()
print('接收请求', addr)
while True:
rec_data = conversation.recv(1024)
if rec_data.decode('utf-8') == '1':
with open('image_file/ling.png', 'rb')as f:
content = f.read()
conversation.send(content)
elif rec_data.decode('utf-8') == '2':
with open('image_file/a.json','r')as f:
content1 = json.loads(f)
conversation.send(content1)
elif rec_data.decode('utf-8') == '3':
content2 = ('拜拜').encode('utf-8')
conversation.send(content2)
break
conversation.close()
客户端
import socket
client = socket.socket()
client.connect(('10.7.187.123', 9990))
send_data = input('请输入命令编号:')
client.send(send_data.encode('utf-8'))
# rec_data1 = client.recv(1024)
# print(rec_data1.decode('utf-8'))
data = bytes()
while True:
rec_data = client.recv(1024)
data += rec_data
if not rec_data:
break
with open('angle.jpg', 'wb')as f:
f.write(data)