2017-12-09 10 views
0

파이썬으로 소켓 프로그래밍을 배우려고합니다. 간단한 웹 서버를 만들었고 브라우저에 연결할 수 있습니다. html 파일을 열어 보냈지 만 브라우저에 표시되지 않습니다.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을 받고에 대한 몇 가지 도움을 싶지만 파일을 브라우저에 올바르게 표시하십시오.

답변

0

나는 스크립트를 정상적으로 작동 시키려고 노력했습니다. 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() 

결과

enter image description here