python套接字服务器使用http协议

时间:2016-11-14 18:33:00

标签: python sockets http networking server

我已经开始使用python学习网络编程了,我的服务器出了点问题。

我正在尝试构建一个简单的服务器,可以用一些图像,js和css代表简单的服务器,但是我无法弄清楚我的文件传输代码有什么问题,所以在我google之后我放弃了一个多小时。 我通过浏览器检查,它发送的html很好,但在页面的上半部分有JS代码。当我试图单独请求图像时,浏览器下载了" name_I_choose.jpg"文件,但它是0kb文件。

这是我的代码:

import socket
import os

print "server on"
server_socket = socket.socket()
server_socket.bind(("127.0.0.1", 80))
server_socket.listen(10)
while True:
    (client_socket, client_address) = server_socket.accept()
    try:
        data = client_socket.recv(1024)
        # print data
    except socket.error:
        print "no more requests, bye"
        break
    if not data:
        break
    lines = data.split("\r\n")
    print lines[0]
    parts = lines[0].split(" ")
    print "1: " + parts[0] + " 2: " + parts[1] + " 3: " + parts[2]
    if parts[0] == "GET" and parts[2] == "HTTP/1.1":
        print "good"
        if parts[1] == "\\" or parts[1] == "/":
            path = "path/to/root/index.html"
        else:
            path = "path/to/root" + parts[1].replace("\\", "/")
        if os.path.isfile(path):
            f = file(path, 'rb')
            size = b = os.path.getsize(path)
            print size
            types = {"txt": "text/html; charset=utf-8", "html": "text/html; charset=utf-8", "jpg": "image/jpeg",
                     "js": "text/javascript; charset=utf-8", "css": "text/css"}
            f_type = types.get(path.split(".")[1])
            data = f.read(size)
            print "sending data"
            client_socket.send("HTTP/1.0 200 " + str(size) + "\r\n" + "Content-Type: " + f_type)
            client_socket.send(data)
        else:
            print "file not found"
            print path
            client_socket.send("HTTP/1.0 404 -1\r\n")
    else:
        print "not GET HTML FORM"
    break
print "done"
client_socket.close()
server_socket.close()

可能存在很多问题,所以我会很感激您所建议的一切。谢谢:))

1 个答案:

答案 0 :(得分:0)

所以最后我解决了,事实证明问题出在文件阅读上。 正确的操作是:

with open(path, 'rb') as infile:
            d = infile.read(1024)
            while d:
                try:
                    client_socket.send(d)
                except socket.error, msg:
                    print "socket error occurred: ", msg
                d = infile.read(1024)