# coding:utf-8
import socket
EOL1 = b'\n\n'
EOL2 = b'\n\r\n'
body = '''Hello444,world! <h1> from the5fire 《Django企业开发实战》</h1>'''
response_params = [
'HTTP/1.1 200 OK',
'Date: Sun, 27 may 2018 01:01:01 GMT',
'Content-Type: text/html; charset=utf-8',
'Content-Length: {}\r\n'.format(len(body.encode())),
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)
print(request)
conn.send(response.encode())
conn.close()
def main():
# socket.AF_INET用于服务器与服务器之间的网络通信
# socket.SOCK_STREAM用于基于TCP的流式socket通信
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置端口可复用,保证我们每次按下Ctrl+C组合键之后,快速重启
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversocket.bind(('127.0.0.1', 8000))
serversocket.listen(5) # 设置backlog--socket连接最大排队数量
print('http://127.0.0.1:8000')
try:
while True:
conn, addr = serversocket.accept()
handle_connection(conn, addr)
finally:
serversocket.close()
if __name__ == '__main__':
main()
多线程版的Web Werver
# coding:utf-8
import errno
import socket
import threading
import time
EOL1 = b'\n\n'
EOL2 = b'\n\r\n'
body = '''Hello444,world! <h1> from the5fire 《Django企业开发实战》</h1>'''
response_params = [
'HTTP/1.1 200 OK',
'Date: Sun, 27 may 2018 01:01:01 GMT',
'Content-Type: text/html; charset=utf-8',
'Content-Length: {}\r\n'.format(len(body.encode())),
body,
]
response = '\r\n'.join(response_params)
def handle_connection(conn, addr):
print('oh, new conn', conn, addr)
time.sleep(30)
request = b""
while EOL1 not in request and EOL2 not in request:
request += conn.recv(1024)
print(request)
conn.send(response.encode())
conn.close()
def main():
# socket.AF_INET用于服务器与服务器之间的网络通信
# socket.SOCK_STREAM用于基于TCP的流式socket通信
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置端口可复用,保证我们每次按下Ctrl+C组合键之后,快速重启
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversocket.bind(('127.0.0.1', 8000))
serversocket.listen(5) # 设置backlog--socket连接最大排队数量
print('http://127.0.0.1:8000')
serversocket.setblocking(0) # 设置socket为非阻塞模式
try:
i = 0
while True:
try:
conn, addr = serversocket.accept()
except socket.error as e:
if e.args[0] != errno.WSAEWOULDBLOCK:
raise
continue
i += 1
print(i)
t = threading.Thread(target=handle_connection, args=(conn, addr), name='thread-%s' %i)
t.start()
finally:
serversocket.close()
if __name__ == '__main__':
main()