代码改变世界

web本质

2017-06-01 00:01  Dr.CoCo  阅读(223)  评论(0编辑  收藏  举报

python-socket服务器

import socket

def handle_request(client):
    buf = client.recv(1024)
    client.send(bytes("HTTP/1.1 200 OK\r\n\r\n",encoding="UTF-8"))
    client.send(bytes("hello,coco~!",encoding="UTF-8"))

def main():
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.bind(('localhost',8090))
    sock.listen(2)

    while True:
        connection,address = sock.accept()
        handle_request(connection)
        connection.close()

if __name__ == '__main__':
    main()

 

将输入的字符串,可以写到单独的文件里 #index

<h1 style='background-color:pink'>hello,coco~!</h1>
<h1 style='background-color:gray'>hello,yoyo~!</h1>

后端程序读取,并赋值给变量

import socket

def handle_request(client):
    buf = client.recv(1024)
    client.send(bytes("HTTP/1.1 200 OK\r\n\r\n",encoding="UTF-8"))
    f = open('index','rb')
    data = f.read()
    f.close()
    client.send(data)

def main():
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.bind(('localhost',8090))
    sock.listen(2)

    while True:
        connection,address = sock.accept()
        handle_request(connection)
        connection.close()

if __name__ == '__main__':
    main()

 

效果:

 

 总结:所有的web服务器(nginx、apache...)本质上都是socket服务器,浏览器充当的就是socket客户端。