一个简单的Web Server

通过socket编程实现的Web服务代码

import errno
import socket
import threading
import time

EOL1 = b'\n\r'
EOL2 = b'\n\r\n'
body = '''Hello,world  -from {thread_name}'''
response_params = [
    'HTTP/1.0 200 OK',
    'Date: Sun, 27 may 2018 01:01:01 GMT',
    'Content-Type: text/html; charset=utf-8',
    'Content-Length: {length}\r\n',
    body,
]
response = '\r\n'.join(response_params)


def handle_connection(conn, addr):
    request = b""
    while EOL1 not in request and EOL2 not in request:
        request += conn.recv(1024)
    current_thread = threading.currentThread()
    content_length = len(body.format(thread_name=current_thread.name).encode())
    print(current_thread.name)
    conn.send(response.format(thread_name=current_thread.name, length=content_length).encode())
    conn.close()


def main():
    # socket.AF_INET 用于服务器与服务器之间的网络通信
    # socket.SOCK_STREAM 用于基于TCP的流式socket通信
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serversocket.bind(('127.0.0.1', 8000))
    serversocket.listen(10)
    print('http://127.0.0.1:8000')
    #serversocket.setblocking(0)  # 设置socket为非阻塞模式
    serversocket.setblocking(1)  # 设置socket为阻塞模式

    try:
        i = 0
        while True:
            try:
                conn, address = serversocket.accept()
            except socket.error as e:
                if e.args[0] != errno.EAGAIN:
                    raise
                continue
            i += 1
            t = threading.Thread(target=handle_connection, args=(conn, address), name='threading-%s' % i)
            t.start()
    finally:
        serversocket.close()


if __name__ == "__main__":
    main()

我们不需要写客户端的代码,因为我们的浏览器就是客户端。

你可能感兴趣的:(django学习)