2017-12-09 12 views
0

私はPythonでソケットプログラミングを学ぼうとしています。私は簡単なWebサーバーを作成しました。私はhtmlファイルを開いて送信しましたが、ブラウザーには表示されません。HTMLページがPythonソケットプログラミングを使用して表示されない

私の簡単なウェブサーバ

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を取得する上でいくつかの助けが好きですブラウザに正しく表示されるようにしてください。

答えて

0

あなたのスクリプトはうまくいきました。 おそらくfilenameの値をチェックする必要があります。

注:htmlファイルのすべての文字列が送信されていることを確認してください。ブラウザ

enter image description here

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() 

結果

関連する問題