Python之tcp server模拟Http通信

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         # 为了兼容所有的浏览器约定浏览器中的换行为\r\n
17         respond = 'GET HTTP/1.1\r\n'
18         respond += '\r\n'
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\r\nHost: 127.0.0.1:6699\r\nUser-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1\r\nCache-Control: max-age=0\r\n\r\n'

posted @ 2018-10-21 20:14  非法关键字  阅读(1902)  评论(0编辑  收藏  举报