do_tcp.py 656 B

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import socket
  4. # 创建一个socket:
  5. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  6. # 建立连接:
  7. s.connect(('www.sina.com.cn', 80))
  8. # 发送数据:
  9. s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')
  10. # 接收数据:
  11. buffer = []
  12. while True:
  13. # 每次最多接收1k字节:
  14. d = s.recv(1024)
  15. if d:
  16. buffer.append(d)
  17. else:
  18. break
  19. data = b''.join(buffer)
  20. # 关闭连接:
  21. s.close()
  22. header, html = data.split(b'\r\n\r\n', 1)
  23. print(header.decode('utf-8'))
  24. # 把接收的数据写入文件:
  25. with open('sina.html', 'wb') as f:
  26. f.write(html)