python最原始服务器
import socket
def handle_request(client):
buf = client.recv(1024)
client.send("HTTP/1.1 200 OK\r\n\r\n".encode('utf-8'))
client.send("Holle".encode('utf-8'))
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 8000))
sock.listen(5)
while True:
connection, address = sock.accept()
handle_request(connection)
connection.close()
if __name__ == '__main__':
main()
利用python模块进行创建服务器
from wsgiref.simple_server import make_server
def RunServer(environ, start_response):
# environ 客户发来的所有数据
# start_response 封装要返回给用户的数据,响应有状态
start_response('200 OK', [('Content-Type', 'text/html')])
# 返回的内容
return [bytes('<h1>Hello, web!</h1>', encoding='utf-8'), ]
if __name__ == '__main__':
httpd = make_server('', 8000, RunServer)
print("Serving HTTP on port 8000...")
httpd.serve_forever()