第一題:
寫一個客戶端和服務器的套接字:
客戶端連接服務器后展示界面:
===========================
- 需要圖片
- 需要文字
- 通知結束
==========================
請選擇:
如果客戶端選1,服務器給客戶端發送一張圖片,客戶端保存圖片到本地
如果客戶端選2, 服務器輸入一段文字發送給客戶端, 客戶端將文字保存在一個message.txt文件中
如果客戶端選3,通知服務器關閉連接,并且客戶端結束
服務器:
import socket
server=socket.socket()
server.bind(('10.7.156.59',8080))
server.listen()
while True:
conversation, addr = server.accept()
print(addr)
while True:
data = conversation.recv(1024)
re_message = data.decode('utf-8')
print(re_message)
if re_message=='1':
print('=====')
with open('./luffy4.jpg','rb') as f:
content=f.read()
conversation.send(content)
conversation.close()
elif re_message=='2':
content='多個瑟瑟發抖是'
conversation.send(content.encode('utf-8'))
conversation.close()
elif re_message == '3':
print('關閉')
conversation.close()
客戶端:
import socket
client = socket.socket()
client.connect(('10.7.156.59', 8080))
print('===========================\n1. 需要圖片\n2. 需要文字\n3. 通知結束\n==========================')
str1=input('>>>')
client.send(str1.encode())
if str1=='1':
message_re = client.recv(1024)
data = bytes()
while message_re:
data += message_re
message_re = client.recv(1024)
with open('./new.jpg', 'bw') as f:
f.write(data)
print('接收完成')
if str1=='2':
message_re=client.recv(1024)
print(message_re.decode('utf-8'))
with open('./message.txt','w',encoding='utf-8')as f:
f.write(message_re.decode('utf-8'))
print('接收完成')
if str1=='3':
print('關閉')
client.close()
第二題:
請求接口: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')
contents=response.json()
list1 = []
for dict1 in contents['data']:
dictionary = {}
dictionary['name'] = dict1['name']
dictionary['text'] = dict1['text']
list1.append(dictionary)
list1 = str(list1)
with open('./files/data.json', 'w', encoding='utf-8')as f:
json.dump(list1, f)
with open('./files/data.json', 'r', encoding='utf-8')as f:
print(json.load(f))