1.python tcp server代码:
1 import socket 2 3 4 def main(): 5 tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 6 tcp_server_socket.bind(('', 6699)) 7 tcp_server_socket.listen(128) 8 9 while True: 10 new_client_socket, new_client_addr = tcp_server_socket.accept() 11 # 接收浏览器请求 12 request = new_client_socket.recv(1024) 13 print(request) 14 15 # 响应浏览器请求 16 # 为了兼容所有的浏览器约定浏览器中的换行为 17 respond = 'GET HTTP/1.1 ' 18 respond += ' ' 19 respond += '<h2>Hello Python</h2>' 20 new_client_socket.send(respond.encode('utf=8')) 21 new_client_socket.close() 22 23 tcp_server_socket.close() 24 25 26 if __name__ == '__main__': 27 main()
终端显示:
1 b'GET / HTTP/1.1 Host: 127.0.0.1:6699 User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Upgrade-Insecure-Requests: 1 Cache-Control: max-age=0 '