在python中手动实现HTTP GET

时间:2012-04-12 22:45:52

标签: python http get

我正在尝试在python中为一个类实现一个简单的HTTP Web服务器,而且我被卡住了。目前我已经硬编码以使事情变得更容易,但我无法弄清楚它为什么不起作用。

#Python 2
import socket
import threading

class socketEcho(threading.Thread):
  def __init__(self,conn):
    super(socketEcho,self).__init__()
    self.conn = conn

  def run(self):
    while 1:
      data = self.conn.recv(1024)
      if not data: 
        print 'Break'
        break
      data = """GET /index.html HTTP/1.1 
      host: www.esqsoft.globalservers.com

      """
      dataList = data.split()
      URI = dataList[1]
      URI = URI[1:]
      hostAddress = dataList[4]    
      try:
        file = open(URI,'r').read()
        result = "HTTP/1.1 200 OK \r\nContent-Type: text/html\r\n\r\n"
        result = result + file
      except IOError as e: #HTTP 404
        print "Error"
        pass    
      #conn.send(data)
      print "Sending"
      print result
      try:
        self.conn.send(result)
      except:
        print "Send Error"
    HOST = ''
    PORT = 50420
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST,PORT))
    s.listen(2) #Blocks, accept only one connection
    while True:
      newSock, addr = s.accept()
      print 'Connected by', addr
      newConn = socketEcho(newSock)
      newConn.start()

当我尝试将我的borswer(firefox)发送到localhost:50420时,它获得200 OK代码就好了,但是它只是在那里等待并且从不显示页面。因为我已经查看了结果变量的打印,看起来很好,所以我不知道是什么,有什么建议吗?这是在结果变量发送之前打印出来的结果。

HTTP/1.1 200 OK 
Content-Type: text/html

<html>

    <head>
    </head>

    <body>

        <h1>Hello World</h1>
        <p>Yes, this does indeed work</p>
        <p><a href="http://www.google.com">Google</a></p>
        <!--<a href="http://knuth.luther.edu/~ranuha01/hello.html">Link Test</a>-->
        <!--<img src="earth.jpg" alt="Earth picture" height="100">-->
        <ul>
            <li><b>One</b></li>
            <ul>
                <li>One and a half</li>
            </ul>
            <li><b>Two</b></li>
        </ul>

    </body>

</html>

1 个答案:

答案 0 :(得分:0)

首先,你应该关闭处理程序中的conn;第二,不要在运行中放置一个循环(self),事件循环是主要的。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Python 2
import socket
import threading

class socketEcho(threading.Thread):
  def __init__(self,conn):
      super(socketEcho,self).__init__()
      self.conn = conn

  def run(self):
      data = self.conn.recv(1024)
      if not data: 
        print 'Break'
        self.conn.close()
        return
      data = """GET /index.html HTTP/1.1 
      host: www.esqsoft.globalservers.com

      """
      dataList = data.split()
      URI = dataList[1]
      URI = URI[1:]
      hostAddress = dataList[4]    
      try:
        file = open(URI,'r').read()
        result = "HTTP/1.1 200 OK \r\nContent-Type: text/html\r\n\r\n"
        result = result + file
      except IOError as e: #HTTP 404
        print "Error"
        pass    
      #conn.send(data)
      print "Sending"
      print result
      try:
        self.conn.send(result)
        self.conn.close()
      except:
        print "Send Error"

HOST = ''
PORT = 50420
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(2) #Blocks, accept only one connection
while True:
  newSock, addr = s.accept()
  print 'Connected by', addr
  newConn = socketEcho(newSock)
  newConn.start()