[英]HTML Page not displaying using Python Socket Programming
我正在嘗試使用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()
index.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()
在瀏覽器上的結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.