Section XVIII single-threaded, single-threaded, non-blocking, long link

import socket

"""
Short link: data transfer three, pass a four waved to conduct a three-way handshake, and then a transfer, then create a three-way handshake fourth wave ......
Long Link: Link established only once, three data transfer
"""

def tcp_serve(resp_socket):
    resp_body = ' hahaha ' 
    resp_header = ' the HTTP / 1.1 200 is the OK \ R & lt \ n- ' + ' the Content-the Length:% D \ R & lt \ n- ' % len (resp_body) + " \ R & lt \ n- " + " \ R & lt \ n- "  
    # 'Content-the length, this parameter tells the browser how long data transmission, in order to determine whether the data browser to accept complete 
    resp_data = resp_header + resp_body
    resp_socket.send(resp_data.encode('utf-8'))

def main():

    web_socket = socket.socket, (socket.AF_INET, socket.SOCK_STREAM),
    web_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    web_socket.bind(('192.168.0.106',8080))
    web_socket.listen(128)
    web_socket.setblocking(False)
    client_socket_list = list()

    while True:    
        try:
            resp_socket, resp_addr = web_socket.accept()        
        except Exception as e:
            pass
        else:
            resp_socket.setblocking(False)
            client_socket_list.append(resp_socket)
            for client_socket in client_socket_list:
                try:
                    recv_data = client_socket.recv(1024)
                except Exception as e:
                    pass
                else:
                    if recv_data:
                        tcp_serve(client_socket)
                        print(recv_data)
                    else:
                        client_socket.close()
                        client_socket_list.remove(client_socket)
    web_socket.close()

if __name__ == '__main__':
    main()

 

Guess you like

Origin www.cnblogs.com/kogmaw/p/12602513.html