作業:
第一題:
寫一個客戶端和服務器的套接字:
客戶端連接服務器后展示界面:
===========================
- 需要圖片
- 需要文字
- 通知結束
==========================
請選擇:
如果客戶端選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)