第一题:
写一个客户端和服务器的套接字:
客户端连接服务器后展示界面:
===========================
- 需要图片
- 需要文字
-
通知结束
请选择:
如果客户端选1,服务器给客户端发送一张图片,客户端保存图片到本地
如果客户端选2, 服务器输入一段文字发送给客户端, 客户端将文字保存在一个message.txt文件中
如果客户端选3,通知服务器关闭连接,并且客户端结束
服务器:
import socket
server = socket.socket()
server.bind(('10.7.156.115', 1024))
server.listen(512)
def send_picture():
name = input('请输入要发送的图片名:')
with open('./files/'+name, 'rb') as f:
while True:
picture = f.read(1024**3)
# 发送完成后发送确认信息
if not picture:
print('图片发送完成!')
conversation.send('图片发送完成!'.encode(encoding='utf-8'))
break
conversation.send(picture)
# conversation.close()
def send_text():
text = input('请输入要传输的文字:')
conversation.send(text.encode(encoding='utf-8'))
# conversation.close()
while True:
print('开始监听!')
conversation, addr = server.accept()
print('收到会话请求!')
while True:
content = conversation.recv(1024).decode('utf-8')
if content == '1':
send_picture()
elif content == '2':
send_text()
elif content == '3':
conversation.close()
print('已经断开会话!')
break
客户端:
import socket
client = socket.socket()
client.connect(('10.7.156.115', 1024))
with open('./files/interface.txt', 'r', encoding='utf-8') as f:
interface = f.read()
def recv_picture():
content = client.recv(1024**3)
data = bytes()
while content:
data += content
content = client.recv(1024**3)
# 发送完成后根据确认信息关闭接收
if content == '图片发送完成!'.encode(encoding='utf-8'):
print('图片接收完成')
break
name = input('请输入您想保持的图片名:')
with open('./files/'+name, 'wb') as f:
f.write(data)
def rece_text():
message = client.recv(1024).decode('utf-8')
with open('./files/message.txt', 'a', encoding='utf-8') as f:
f.write(message + '\n')
while True:
print(interface)
value = input('请选择(1-3):')
client.send(value.encode(encoding='utf-8'))
if value == '1':
recv_picture()
continue
elif value == '2':
rece_text()
continue
elif value == '3':
client.send('请关闭会话!'.encode(encoding='utf-8'))
client.close()
break
else:
print('请输入正确的选项!')
continue
第二题:
请求接口:https://www.apiopen.top/satinApi?type=1&page=1 获取网络数据。
将内容中所有的name和text对应的值取出,并且保存到一个json文件中,保存的格式:
[{“name”:”张三”, “text”:”哈哈,让我们一起自由的飞翔”}, {“name”:”喒你家玻璃”, “text”:”截图暂停,截到的将会是对你爱情的预言三词!”}]
import requests
import re
import json
url = 'https://www.apiopen.top/satinApi?type=1&page=1'
response = requests.get(url)
re_str = r'"text":"(.*?)","user_id":.*?"name":"(.*?)","screen_name":'
content = re.findall(re_str, response.text)
# print(content)
list1 = []
for item in content:
dict1 = {'name': '', 'text': ''}
dict1['name'] = item[1]
dict1['text'] = item[0]
list1.append(dict1)
with open('./files/api_text.json', 'w', encoding='utf-8') as f:
json.dump(list1, f)
with open('./files/api_text.json', 'r', encoding='utf-8') as f:
content = json.load(f)
print(content)