2014-01-16 2 views
1

Я пытаюсь изучить некоторые материалы HTTP/CGI, и я хочу распечатать HTML на веб-странице, когда вы просматриваете его в своем браузере, но я не уверен, какой правильный синтаксис при использовании библиотеки сокетов:Отправка HTML через сервер Socket Python

#!/usr/bin/env python 
import random 
import socket 
import time 

s = socket.socket()   # Create a socket object 
host = socket.getfqdn() # Get local machine name 
port = 9082 
s.bind((host, port))  # Bind to the port 

print 'Starting server on', host, port 
print 'The Web server URL for this would be http://%s:%d/' % (host, port) 

s.listen(5)     # Now wait for client connection. 

print 'Entering infinite loop; hit CTRL-C to exit' 
while True: 
    # Establish connection with client.  
    c, (client_host, client_port) = s.accept() 
    print 'Got connection from', client_host, client_port 
    c.send('Server Online\n') 
    c.send('HTTP/1.0 200 OK\n') 
    c.send('Content-Type: text/html\n') 
    c.send(' """\ 
     <html> 
     <body> 
     <h1>Hello World</h1> this is my server! 
     </body> 
     </html> 
     """ ') 
    c.close() 

первые три c.send линии работы, а затем есть проблема синтаксиса с последней строки, где я положил в HTML.

ответ

3

Использование тройной кавычки строка:

c.send(""" 
    <html> 
    <body> 
    <h1>Hello World</h1> this is my server! 
    </body> 
    </html> 
""") # Use triple-quote string. 

Помимо синтаксических ошибок, есть несколько вопросов в коде. Ниже приводится измененный вариант (в то время как только петля см комментарии, чтобы увидеть, что модификация сделал)

while True: 
    # Establish connection with client.  
    c, (client_host, client_port) = s.accept() 
    print 'Got connection from', client_host, client_port 
    #c.send('Server Online\n') # This is invalid HTTP header 
    c.recv(1000) # should receive request from client. (GET ....) 
    c.send('HTTP/1.0 200 OK\n') 
    c.send('Content-Type: text/html\n') 
    c.send('\n') # header and body should be separated by additional newline 
    c.send(""" 
     <html> 
     <body> 
     <h1>Hello World</h1> this is my server! 
     </body> 
     </html> 
    """) # Use triple-quote string. 
    c.close() 
+0

Он печатает привет мир линии, но по какой-то причине не печатает c.send ('HTTP/1.0 200 OK \ n ') c.send (' Content-Type: text/html \ n ') – Goose

+2

@Goose, это HTTP-заголовки. Они не печатаются в браузере. – falsetru

+0

@Goose. Вы можете проверить HTTP-заголовки, используя функцию отладки браузера. (Firebug для Firebug, инструменты разработчика в Chrome, ...) – falsetru

Смежные вопросы