服务器端:
import socket
server = socket.socket()
server.bind(("10.7.156.69",17892))
server.listen(512)
#保持服务器一直运行
while True:
client,user = server.accept()
s = "================\n1、发送图片\n2、发送文字\n3、通知结束\n==================="
client.send(s.encode("utf-8"))
#保持通信
while True:
message_re = client.recv(1024).decode("utf-8")
if message_re == "1":
with open("./147014999.jpg","rb") as f:
image = f.read()
client.send(image)
client.close() #断开会话
elif message_re == "2":
client.send("你怎么这么帅!".encode("utf-8"))
client.close()
elif message_re == "3":
client.send("感谢使用,再见".encode("utf-8"))
client.close()
break
client.close()
break
客服端
import socket
#1、创建套接字对象默认 使用IPv4和TCP协议
client = socket.socket()
#2、连接到服务器(需要指定IP地址和端口)
client.connect(("10.7.156.69",17892))
print(client.recv(1024).decode("utf-8"))
while True:
message = input("请输入选择:")
#想服务器发送数据
client.send(message.encode("utf-8"))
data = bytes()
image = client.recv(1024)
if message == "1":
f = open("./aa.jpg", "wb")
while image:
data += image
image = client.recv(1024)
print("正在接收................")
f.write(data)
f.close()
print("接收完成")
elif message == "2":
with open("./aa.txt","w",encoding="utf-8") as f:
f.write(image.decode("utf-8"))
f.close()
elif message == "3":
print(client.recv(1024).decode("utf-8"))
break
# 3、从服务器接收数据
#print(client.recv(1024).decode("utf-8"))
#4、断开连接
requests练习
import requests
import json
for j in range(1,5):
url = "https://www.apiopen.top/satinApi?type=1&page="+str(j)
response = requests.get(url)
data = json.loads(response.text)
with open(r"./homework2.json","w",encoding="utf-8") as f:
l =[]
for i in data["data"]:
d = {}
d["name"]=i["name"]
d["text"] = i["text"]
l.append(d)
json.dump(l,f)