t3

本文介绍了一个使用Python编写的简易HTTP服务器。该服务器能够处理GET请求,并返回简单的HTML页面或者图片内容。通过监听本地地址127.0.0.1的8888端口,服务器可以提供静态资源,如文本和图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#! /usr/bin/python2
# coding=utf-8
# Written by Vamei

import socket
import time

# Address

HOST = '127.0.0.1'
PORT = 8888


def read_file(file_name):
    print "---------------------------",file_name
    f = open('test.jpg', 'rb')
    pic_content = '''\nHTTP/1.x 200 OK\nContent-Type: image/gif\n\n'''
    pic_content = pic_content + f.read()
    f.close()
    return pic_content


# Prepare HTTP response
text_content = '''HTTP/1.x 200 OK
Content-Type: text/html; charset=utf-8

<head>
<title>WOWzh啊士大夫</title>
</head>
<html>
<p>Wow, Pythond大跌 Server</p>

</html>
'''


# Read picture, put into HTTP format
f = open('test.jpg', 'rb')
pic_content = '''
HTTP/1.x 200 OK
Content-Type: image/gif

'''
pic_content = pic_content + f.read()
f.close()


# Configure socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))


pic_content2 = read_file("test.jpg")
# infinite loop, server forever
while True:
    # 3: maximum number of requests waiting
    s.listen(3)
    conn, addr = s.accept()
    request = conn.recv(1024)
    method = request.split(' ')[0]
    src = request.split(' ')[1]
    print src
    # deal with GET method
    if method == 'GET':
        # ULR
        if src == '/test.jpg':
            content = pic_content2
        else:
            content = text_content

        print 'Connected by', addr
        print 'Request is:', request
        #print 'content is:', content
        if (pic_content == pic_content2):
            print "==",len(pic_content2),len(pic_content)
        else:
            print "!=",len(pic_content2),len(pic_content)
        with open("a1.txt", 'wb') as f:
            f.write(pic_content)
        with open("a2.txt", 'wb') as f:
            f.write(pic_content2)

        conn.sendall(content)
    # close connection
    conn.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值