作业:
第一题:
写一个客户端和服务器的套接字:
客户端连接服务器后展示界面:
===========================
- 需要图片
- 需要文字
- 通知结束
==========================
请选择:
如果客户端选1,服务器给客户端发送一张图片,客户端保存图片到本地
如果客户端选2, 服务器输入一段文字发送给客户端, 客户端将文字保存在一个message.txt文件中
如果客户端选3,通知服务器关闭连接,并且客户端结束
server
import socket
import threading
def func(addr1,conversation1):
while True:
message_re = conversation1.recv(1024).decode('utf-8')
if message_re == '1':
with open('./Django迁移.png','rb') as f:
img = f.read()
conversation1.send(img)
elif message_re == '2':
text = input('请输入:')
conversation1.send(text.encode('utf-8'))
elif message_re == '3':
conversation.close()
exit()
else:
pass
server = socket.socket()
server.bind(("10.7.156.108",10020))
server.listen(10)
while True:
conversation, addr = server.accept()
threading.Thread(target=func, args=(addr, conversation)).start()
client
import socket
client = socket.socket()
client.connect(("10.7.156.108",10020))
while True:
with open('./1-view.txt','rb') as f:
print(f.read().decode('utf-8'))
option = input("请输入操作码:")
if option == '1':
client.send('1'.encode('utf-8'))
message = client.recv(1024000)
with open('./00.png','wb') as f:
f.write(message)
print('图片下载完成!')
elif option == '2':
client.send('2'.encode('utf-8'))
message = client.recv(1024000).decode('utf-8')
with open('./message.txt','wb') as f:
f.write(message.encode('utf-8'))
print('文本保存完成!')
elif option == '3':
client.send('3'.encode('utf-8'))
break
else:
print('操作码错误!!!')
# client.send(input('>>>').encode('utf-8'))
# message = client.recv(1024).decode("utf-8")
# if message != '':
# print(message)
第二题:
请求接口:https://www.apiopen.top/satinApi?type=1&page=1 获取网络数据。
将内容中所有的name和text对应的值取出,并且保存到一个json文件中,保存的格式:
[{“name”:”张三”, “text”:”哈哈,让我们一起自由的飞翔”}, {“name”:”喒你家玻璃”, “text”:”截图暂停,截到的将会是对你爱情的预言三词!”}]
import requests
import json
response = requests.get('https://www.apiopen.top/satinApi?type=1&page=1')
text = json.loads(response.text)
# print(text)
res = []
for i in text['data']:
res.append({'name':i['name'],'text':i['text']})
with open('./data.json','w') as f:
json.dump(res,f)
网友评论