I'm trying to learn socket programming with python, and I've created a simple webserver, and I can connect to it in my browswer. I've opened an html file and send it, but it's not displaying in the browswer.
My simple webserver
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>
I'm very new at this, so I'm probably just missing a very minute details, but I'd love some help on getting the html file to correctly display in the browser.
I've tried your script works fine by the way. Maybe you need to check the filename
value.
note: little change to make sure all strings on html file sent.
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()
Result on browser
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.