这是服务器代码:
import socket
import os
ROUTES = [
"/",
"/index",
"/favicon.ico",
"/blog",
"/api"
]
FAVICON = "favicon.ico"
def getResponse(method,route):
bmsg = b""
if method == "GET":
if route in ROUTES:
if "/favicon.ico" == route:
if os.path.exists(FAVICON):
with open(FAVICON,"rb") as f:
data = f.read()
bmsg = "HTTP/1.1 200 OK\nContent-Type: image/ico\nContent-Length: ".encode("utf-8")+ str(len(data)).encode("utf-8") + "\r\n\r\n".encode("utf-8")
bmsg += data
if "/blog" == route:
data = "<h1><p>Blog Page</p></h1><p><a href=\"/index\">Back to main page</a></p>".encode("utf-8")
bmsg = "HTTP/1.1 200 OK\nContent-Type: text/html; charset=utf-8\nContent-Length: ".encode("utf-8") + str(len(data)).encode("utf-8") + "\r\n\r\n".encode("utf-8") + data
if "/" == route or "/index" == route:
data = "<h1><p>Index Page</p></h1>".encode("utf-8")
bmsg = "HTTP/1.1 200 OK\nContent-Type: text/html; charset=utf-8\nContent-Length: ".encode("utf-8") + str(len(data)).encode("utf-8") + "\r\n\r\n".encode("utf-8") + data
if "/api" == route:
data = "{\"server_message\":\"OK\"}".encode("utf-8")
bmsg = "HTTP/1.1 200 OK\nContent-Type: application/json\nContent-Length: ".encode("utf-8") + str(len(data)).encode("utf-8") + "\r\n\r\n".encode("utf-8") + data
else:
data = "<h2>404</h2><h1><p>Not Found</p></h1>".encode("utf-8")
bmsg = "HTTP/1.1 404 false\nContent-Type: text/html; charset=utf-8\nContent-Length: ".encode("utf-8") + str(len(data)).encode("utf-8") + "\r\n\r\n".encode("utf-8") + data
else:
data = "<h2>405</h2><h1><p>Method not allowed</p></h2>".encode("utf-8")
bmsg = "HTTP/1.1 405 false\nContent-Type: text/html; charset=utf-8\nContent-Length: ".encode("utf-8") + str(len(data)).encode("utf-8") + "\r\n\r\n".encode("utf-8") + data
return bmsg
def start():
server_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server_sock.bind(("localhost",5000))
server_sock.listen(10)
step = 0
while True:
step += 1
print(step)
client_sock,addr = server_sock.accept()
request = client_sock.recv(4096)
request_list = request.decode("utf-8").split("\n")
for line in request_list:
print(line)
method,route = (request_list[0].split(" ")[0],request_list[0].split(" ")[1])
bmsg = getResponse(method,route)
client_sock.sendall(bmsg)
client_sock.close()
server_sock.close()
start()
这是python代码:
import requests
def get():
msg = '{"command":"C:/GhostAssistent/nircmd.exe setsysvolume 6553"}'.encode("cp1251")
print(msg)
r = requests.get("http://localhost:5000/api",data = msg)
if r.status_code == 200:
print("headers - ",r.headers)
if "application/json" in r.headers.get("content-type"):
print("json - ",r.json())
else:
print("text - ",r.text)
else:
print("some error has happend")
当我使用 Python 脚本发出 GET 请求时,一切都很好,但值得从浏览器发送 GET 请求,因此只有在再次从浏览器发出请求后,我才会收到 Python 脚本的响应。如果在启动服务器后根本不使用浏览器,那么一切都很好 - 我运行 Python 脚本 - 我得到响应,我再次发送请求 - 我再次得到响应。事实证明,浏览器会阻止 python 脚本的连接,直到它收到响应。但他为什么不自己封锁自己呢?我可以打开两个浏览器选项卡并以任何顺序刷新它们,并在我询问时立即获得响应。
无论来自浏览器的请求如何,如何让 python 脚本接收响应?