2014-01-16 34 views
1

我想學習一些HTTP/CGI的東西,並且當您在瀏覽器中查看它時,我想在網頁上打印HTML,但不確定使用套接字庫時正確的語法是什麼:通過Python套接字服務器發送HTML

#!/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循環,請參閱註釋以查看所做的修改)

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

它打印Hello world行,但由於某種原因不打印c.send('HTTP/1.0 200 OK \ n') c.send('Content-Type:text/html \ n') – Goose

+2

@ Goose,它們是HTTP標頭。它們不在瀏覽器中打印。 – falsetru

+0

@ Goose,您可以使用瀏覽器的調試功能來檢查HTTP標頭。 (Firebug for Firebug,Chrome中的開發工具,...) – falsetru

相關問題