python服务器

来源:互联网 发布:mac用什么炒股软件 编辑:程序博客网 时间:2024/06/06 12:22

python最原始服务器

import socketdef 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_serverdef 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()

原创粉丝点击