我正在尝试使用 python 学习套接字编程,并且我创建了一个简单的网络服务器,我可以在我的浏览器中连接到它。我打开了一个 html 文件并发送了它,但它没有显示在浏览器中。
我的简单网络服务器
import socket
import os
# Standard socket stuff:
host = ''
port = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(5)
# Loop forever, listening for requests:
while True:
csock, caddr = sock.accept()
print("Connection from: " + str(caddr))
req = csock.recv(1024) # get the request, 1kB max
print(req)
# Look in the first line of the request for a move command
# A move command should be e.g. 'http://server/move?a=90'
filename = 'static/index.html'
f = open(filename, 'r')
l = f.read(1024)
while (l):
csock.sendall(str.encode("""HTTP/1.0 200 OK\n""",'iso-8859-1'))
csock.sendall(str.encode('Content-Type: text/html\n', 'iso-8859-1'))
csock.send(str.encode('\n'))
csock.sendall(str.encode(""+l+"", 'iso-8859-1'))
print('Sent ', repr(l))
l = f.read(1024)
f.close()
csock.close()
索引.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>This is the body</p>
</body>
</html>
我对此很陌生,所以我可能只是遗漏了一个非常详细的细节,但我希望得到一些帮助,让 html 文件在浏览器中正确显示。
顺便说一下,我试过你的脚本工作正常。也许您需要检查该filename
值。
注意:确保发送 html 文件上的所有字符串几乎没有变化。
import socket
import os
# Standard socket stuff:
host = ''
port = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(5)
# Loop forever, listening for requests:
while True:
csock, caddr = sock.accept()
print("Connection from: " + str(caddr))
req = csock.recv(1024) # get the request, 1kB max
print(req)
# Look in the first line of the request for a move command
# A move command should be e.g. 'http://server/move?a=90'
filename = 'static/index.html'
f = open(filename, 'r')
csock.sendall(str.encode("HTTP/1.0 200 OK\n",'iso-8859-1'))
csock.sendall(str.encode('Content-Type: text/html\n', 'iso-8859-1'))
csock.send(str.encode('\r\n'))
# send data per line
for l in f.readlines():
print('Sent ', repr(l))
csock.sendall(str.encode(""+l+"", 'iso-8859-1'))
l = f.read(1024)
f.close()
csock.close()
浏览器上的结果
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句