我没有使用socketio,但这可能会对你有所帮助。
我为我的 Python 服务器实现了如下:
client, address = sock.accept()
print('[CONNECTED] Client Connected:', address)
req = client.recv(1024).decode('utf8')
req = req.split(' ')[:2]
print('[CONNECTED] New request', req[-1])
client.send(b"HTTP/1.1 200 OK\n")
try:
if req[-1] == '/':
client.send(b'Content-Type: text/html\n\n')
client.sendfile(open('./static/html/home/index.html', 'rb'))
# client.sendfile(open('./static/js/index.js', 'rb'))
else:
if '.js' in req[-1]:
client.send(b'Content-Type: text/javascript\n\n')
elif '.css' in req[-1]:
client.send(b'Content-Type: text/css\n\n')
else:
client.send(b'None')
client.sendfile(open('.' + req[-1], 'rb'))
只需将 html 中的 JS 和/或 CSS 文件称为
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="http://localhost:1573/static/css/styles.css" />
</head>
<body>
Hello World!
<script src="http://localhost:1573/static/js/index.js"></script>
</body>
</html>
项目目录:
./
server.py
static/
html/
index.html
css/
styles.css
js/
index.js
所以基本上我让 HTML 提到脚本作为本地服务器 localhost 文件的一部分,这使得它也发送对这些文件的请求。在服务器中,我检查是否请求 JS 或 CSS 并相应地发送它。请注意,“Content-Type”在这里起着重要作用。将 JS 作为 JS 和 CSS 作为 CSS 而不是纯文本发送。