在python中手动实现httpget

2024-09-24 22:22:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python为一个类实现一个简单的httpwebserver,但我遇到了困难。目前我已经把它硬编码好让事情更简单,但我不明白为什么它不起作用。在

#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()

当我尝试将我的浏览器(firefox)发送到本地主机:50420 it获取200个OK代码,但它只是在那里等待,从不显示页面。因为我已经看过结果变量的打印结果,它看起来很好,所以我不知道发生了什么,有什么建议吗?这是在发送结果变量之前打印出来的。在

^{pr2}$

Tags: importselfhttpdatainitdefurisocket
1条回答
网友
1楼 · 发布于 2024-09-24 22:22:21

首先,应该关闭处理程序中的conn;其次,不要在run(self)中放置循环,事件循环在main中。在

#!/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()

相关问题 更多 >