python写web服务器教程_python实现简单web服务器

把前面java版的服务器程序用python改写,感觉python果然简洁,限于水平,写的还不够好

因为使用了os.fork(),windows下无法使用,可以改成threading,

t=threading.Thread(target=,args=(args))

t.start()

可以参考廖大的python教程:TCP编程

import os

import signal

import socket

import time

ADDRESS = (HOST, PORT) = '127.0.0.1', 8888

REQUEST_QUEUE_SIZE = 10

def request(client_conn):

request_header=client_conn.recv(1024).decode()

return request_header

def request_source(client_conn):

request_header =request(client_conn)

try:

req_source=request_header.split()[1]

except:

req_source=""

return req_source[1:]

def handle_request(client_conn):

req_source=request_source(client_conn)

if os.path.exists(req_source):

if req_source.endswith('.txt') or req_source.endswith('.html'):

header="HTTP/1.1 200 OK\nContent-type:text/html\n\n"

elif req_source.endswith('.jpeg') or req_source.endswith(".jpg"):

header = "HTTP/1.1 200 OK\nContent-type:image/jpeg\n\n"

elif req_source.endswith('.gif'):

header= "HTTP/1.1 200 OK\nContent-type:image/gif\n\n"

elif req_source.endswith(".css"):

header = "HTTP/1.1 200 OK\nContent-type:text/css\n\n"

elif req_source.endswith(".js"):

header = "HTTP/1.1 200 OK\nContent-type:text/js\n\n"

else:

header = "HTTP/1.1 200 OK\nContent-type:application/octet-stream\n\n"

f = open(req_source,'rb')

content = f.read()

f.close()

client_conn.sendall((header.encode() + content))

else:

content='HTTP/1.1 404 Not Found\n\n

404 Not Found

'

client_conn.send(content.encode('utf-8'))

time.sleep(2)

def signal_handler(signum, frame):

pid, status = os.wait()

print('child pid: %s stopped ,status %s'%(pid,status))

def server():

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# setsockopt(level,optname,value)

# 表示将SO_REUSEADDR标记为TRUE,

# 操作系统会在服务器socket被关闭或服务器进程终止后马上释放该服务器的端口

server_socket.bind(ADDRESS)

server_socket.listen(REQUEST_QUEUE_SIZE)

print('Serving HTTP on port {port} ...'.format(port=PORT))

signal.signal(signal.SIGCHLD, signal_handler)#子进程结束后自动向父进程发送SIGCHLD信号

while True:

client_conn, client_address = server_socket.accept()

pid = os.fork()

if pid == 0: # child

server_socket.close()

handle_request(client_conn)

client_conn.close()

os._exit(0)

else:

client_conn.close()

if __name__ == '__main__':

server()

标签: Python

顶一下

(0)

0%

踩一下

(0)

0%

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值