2013-09-25 6 views
2

파이썬 웹 서버를 실행하려고합니다. 서버가 실행 중이므로 html 텍스트 만 볼 수 있다는 것을 제외하고는 모두 작동한다고 가정합니다. jpeg/image 및 pdf 파일은 표시되지 않습니다. 여기 내가 지금까지 가지고있는 것이있다.웹 서버 : Python에서 TCP 연결을위한 소켓 프로그래밍

#import socket module 
from socket import * 

serverSocket = socket(AF_INET, SOCK_STREAM) 
serverSocket.bind(('', 12000)) 
serverSocket.listen(1) 

while True: 
    print 'Ready to serve...'  
    connectionSocket, addr = serverSocket.accept() 
    print 'Required connection', addr 

    try: 
     message = connectionSocket.recv(1024) 
     filename = message.split()[1] 
     f = open(filename[1:]) 
     outputdata = f.read() 

     #Fill in start 
     connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n') 
     #Fill in end 
     #Send the content of the requested file to the client 
     for i in range(0, len(outputdata)): 
      connectionSocket.send(outputdata[i]) 
      connectionSocket.close() 
    except IOError: 
     #Send response message for file not found 
     #Fill in start 
     connectionSocket.send('404 Not Found')      
     #Fill in end 
     #Close client socket 
     #Fill in start 
     connectionSocket.close()      
     #Fill in end 
     serverSocket.close() 
+0

Btw, try/except : while 블록 내에서 한 들여 쓰기를 이동했습니다. 그렇지 않으면 try 블록이 실행되지 않습니다. –

+2

HTTP 프로토콜 스펙을 읽고 따라하는 것이 좋습니다. 콘텐츠 유형 같은 것이 중요합니다. – vanza

+0

@ManojPandey close() 메서드는 루프에 대한 필요가 없습니다. – RudePeopleStepOff

답변

0

나는 똑같은 작업을하고 있습니다. 바로이 후

connectionSocket.send('Content-Type: image/jpeg') 

:

connectionSocket.send('HTTP/1.0 200 OK') 

나는 우리가 헤더의 일부 라인을 놓치고있어/난 가정 I 라인을 추가했다.