Python-写一个socket客户端

1. 使用requests实现

import requests

r = requests.get('http://www.httpbin.org')
print (r.status_code)
print (r.headers)

200
{‘Date’: ‘Tue, 08 Dec 2020 09:41:06 GMT’, ‘Content-Type’: ‘text/html; charset=utf-8’, ‘Content-Length’: ‘9593’, ‘Connection’: ‘keep-alive’, ‘Server’: ‘gunicorn/19.9.0’, ‘Access-Control-Allow-Origin’: ‘*’, ‘Access-Control-Allow-Credentials’: ‘true’}

使用socket模块实现

# 用socket实现
import socket
#AF_INET:ipv4地址,SOCK_STREAM:tcp协议
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

# debug
print(f's1:{s}')

s1:<socket.socket fd=1184, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0>

s.connect(('www.httpbin.org',80))
# debug
print (f's2:{s}')

s2:<socket.socket fd=1184, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=(‘10.10.15.231’, 62066), raddr=(‘3.211.1.78’, 80)>

s.send(b'GET / HTTP/1.1\r\nHOST:time.geekbang.org\r\nConnection: close\n\r\n')

60

buffer = []

while True:
    data = s.recv(1024)
    if data:
        buffer.append(data)
    else:
        break

s.close()

respose = b''.join(buffer)

header, html = respose.split(b'\r\n\r\n', 1)

print(header.decode('GBK'))

with open('index.html', 'wb') as f:
    f.write(html)

HTTP/1.1 200 OK
Date: Tue, 08 Dec 2020 13:01:56 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 9593
Connection: close
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值