单进程-单线程-非阻塞-长链接

import socket

import re

def service_client(new_socket):

# '''为这个客户端返回数据'''

# 1.接收浏览器发送出来的请求,即HTTP请求

# GET/HTTP/1.1

#

    request_lines = request.splotlines()

print ('')

print ('>>>' *30)

print (request_lines)

ret = re.match(r'[^/]+(/[^ ]*)', request_lines[0])#正则提取

    file_name =''

    if ret:

file_name = ret.group(1)

print ('*' *50, file_name)# !!!!!!!!网页名字

        if file_name ='/index.html'

    # 2.返回HTTP格式的数据给浏览器

    try:

f =open('.../Desktop/项目/项目.html', 'rb')

# f = open('.../Desktop/项目/项目.html' +file_name,'rb')

    except:

response ='HTTP/1.1 404 NOT FOUND\r\n'

        response +='\r\n'

        response +='--FILE NOT FOUND---'

        new_socket.send(response.encode('utf-8'))

else:

html_content = f.read()

f.close()

# 2。1 准备发送给浏览器的Header

        response_header ='HTTP/1.1 200 OK\r\n'

        response_header +='\r\n'

        response_header ='Content-Length : %d\r\n'%len(response_body)

response_header +='\r\n'

        response = response_header.encode('utf-8')+ response_body

#将 Response发送给浏览器

        new_socket.send(response)

def main():

""" 用来完成整提的控制"""

    # 1。创建套接字

    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

tcp_server_socket.setsockopt(socket.SOCK_STREAM, socket.SO_REUSEADDR,1)

# 2。绑定

    tcp_server_socket.bind(('', 7890))

# 3。变为监听套接字(最大链接书128)

    tcp_server_socket.listen(128)

while True:

# 4。等待新客户端的链接

        try:

new_socket, client_addr = tcp_server_socket.accept()

# 局部变量

        except Exception as ret:

pass

        else:

new_socket.setblocking(False)

client_socket_list.append(new_socket)

for client_socketin client_socket_list:

try:

recv_data = client_socket.recv(1024).dacode('utf-8')

except Exception as ret:

pass

            else:

if recv_data:

# 5为这个客户端服务

                    service_client(client_socket,recv_data)

else:

client_socket.close()

client_socket_list.remove(client_socket)

# 6。关闭监听套接字

    tcp_server_socket.close()

if __name__ =='__main__':

main()

作者:斜杠先生_

链接:https://www.jianshu.com/p/9097b79d8d09

来源:

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


你可能感兴趣的:(单进程-单线程-非阻塞-长链接)