我的问题很简单,非常简单。当我在浏览器上键入localhost:9999 / ok.jpg时,我的服务器运行不会显示图像。我可能会遗漏一些服务器设置的概念。
以下是代码:
import socket
import threading
import socketserver
import os
class MyHandler(socketserver.BaseRequestHandler):
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "image/jpg")
self.end_headers()
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "image/jpg")
self.end_headers()
f = open('ok.jpg', 'rb')
self.wfile.write(f.read())
f.close()
class MyServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
def __init__(self, server_adress, RequestHandlerClass):
self.allow_reuse_address = True
socketserver.TCPServer.__init__(self, server_adress, RequestHandlerClass, False)
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
server = MyServer((HOST, PORT), MyHandler)
server.server_bind()
server.server_activate()
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
感谢您提供任何可能的帮助。
答案 0 :(得分:1)
从您的do_GET和do_HEAD方法判断,您似乎真的希望MyHandler
扩展BaseHTTPRequestHandler
http://docs.python.org/2/library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler
BaseRequestHandler
不知道HTTP(这是您的浏览器使用的)。
答案 1 :(得分:0)
更好地使用SimpleHTTPServer:
import SimpleHTTPServer
import SocketServer as socketserver
import os
import threading
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
path_to_image = 'ok.jpg'
img = open(path_to_image, 'rb')
statinfo = os.stat(path_to_image)
img_size = statinfo.st_size
print(img_size)
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "image/jpg")
self.send_header("Content-length", img_size)
self.end_headers()
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "image/jpg")
self.send_header("Content-length", img_size)
self.end_headers()
f = open(path_to_image, 'rb')
self.wfile.write(f.read())
f.close()
class MyServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
def __init__(self, server_adress, RequestHandlerClass):
self.allow_reuse_address = True
socketserver.TCPServer.__init__(self, server_adress, RequestHandlerClass, False)
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
server = MyServer((HOST, PORT), MyHandler)
server.server_bind()
server.server_activate()
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()