作業(yè):
第一題:
寫(xiě)一個(gè)客戶端和服務(wù)器的套接字:
客戶端連接服務(wù)器后展示界面:
===========================
- 需要圖片
- 需要文字
- 通知結(jié)束
==========================
請(qǐng)選擇:
如果客戶端選1潦嘶, 服務(wù)器給客戶端發(fā)送一張圖片盐类,客戶端保存圖片到本地
如果客戶端選2, 服務(wù)器輸入一段文字發(fā)送給客戶端毛雇, 客戶端將文字保存在一個(gè)message.txt文件中
如果客戶端選3赤惊,通知服務(wù)器關(guān)閉連接砰逻,并且客戶端結(jié)束
服務(wù)器端
import socket
# 創(chuàng)建服務(wù)器
server = socket.socket()
# 綁定ip和端口號(hào)
server.bind(('10.10.10.108', 8081))
# 監(jiān)聽(tīng)端口
server.listen(100)
print('開(kāi)始監(jiān)聽(tīng)')
while True:
# 等待連接
print('等待連接')
conversation, addr = server.accept()
print('%s 連接' % addr[0])
with open('./files/main_page.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 客戶端請(qǐng)求 給客戶端發(fā)送主頁(yè)消息
conversation.send(content.encode('utf-8'))
while True:
value = conversation.recv(1024)
value = value.decode('utf-8')
if value == '3':
print('回話結(jié)束')
conversation.close()
continue
elif value == '1':
with open('./files/new.jpg', 'rb') as f:
data_bytes = f.read()
conversation.send(data_bytes)
conversation.close()
print('圖片已發(fā)送')
continue
elif value == '2':
message = '你好嗎旋恼?'
conversation.send(message.encode('utf-8'))
continue
客戶端
import socket
# 創(chuàng)建客戶端
client = socket.socket()
# 連接服務(wù)器
client.connect(('10.10.10.108', 8081))
main_page = client.recv(2048)
# 顯示消息
main_page = main_page.decode('utf-8')
# print(main_page)
# 接收消息
while True:
print(main_page)
value = input('請(qǐng)選擇:')
if value == '3':
client.send('3'.encode('utf-8'))
client.close()
break
# message_re = client.recv(1024)
elif value == '1':
client.send('1'.encode('utf-8'))
message_re = client.recv(1024)
data = bytes()
i = 1
while message_re:
i += 1
# print('接收?qǐng)D片')
data += message_re
message_re = client.recv(1024)
with open('./re_file/re_file.jpg', 'wb') as f:
f.write(data)
print('圖片接收完成')
elif value == '2':
client.send('2'.encode('utf-8'))
message_re = client.recv(1024)
message_re = message_re.decode('utf-8')
with open('./re_file/message.txt', 'w', encoding='utf-8') as f:
f.write(message_re)
print('文字接收完成')
continue
else:
print('輸入錯(cuò)誤乘陪,請(qǐng)重新輸入统台!')
continue
1.png
第二題:
請(qǐng)求接口:https://www.apiopen.top/satinApi?type=1&page=1 獲取網(wǎng)絡(luò)數(shù)據(jù)。
將內(nèi)容中所有的name和text對(duì)應(yīng)的值取出啡邑,并且保存到一個(gè)json文件中贱勃,保存的格式:
[{“name”:”張三”, “text”:”哈哈,讓我們一起自由的飛翔”}, {“name”:”喒你家玻璃”, “text”:”截圖暫停谤逼,截到的將會(huì)是對(duì)你愛(ài)情的預(yù)言三詞贵扰!”}]
import requests
import json
import re
# 請(qǐng)求數(shù)據(jù)
url = 'https://www.apiopen.top/satinApi?type=1&page=1'
result = requests.get(url)
contents = result.text
re_dict = r'({.*?})+?'
results = re.findall(r'\[.*\]', contents)
content1 = results[0][1:-1]
print(content1)
res = re.findall(re_dict, content1)
print(len(res))
content = []
for str1 in res:
name = re.findall(r'"name":".+?"', str1)
texts = re.findall(r'"text":".+?"', str1)
print(name, texts)
content.append({name[0]:texts[0]})
print(content)
with open('./files/data.json', 'w', encoding='utf-8') as f:
json.dump(content, f)
2018-10-24_232310.png