02-socket編程
socket又叫套接字苗膝,指的是實現(xiàn)通信過程的兩個端董栽。等待請求的一端叫服務端套接字椅野,
發(fā)送請求的一端叫客服端套接字
Python中提供socket模塊來支持socket編程
import socket
服務器套接字
1.創(chuàng)建套接字對象
`
socket(family,type)
family,-設置IP類型 AF_INET - ipv4(默認值) AF_INET - ipv6
type-設置傳輸類型 SOCK_STREAM - tcp SOCK_DGRAM-udp
創(chuàng)建一個基于IPV4和tcp的套接字對象
server = socket.socket()
2.綁定IP端口和地址
bind((ip,端口號))
ip - 服務器對應的計算機的IP地址鸣峭,字符串
端口號 - 用來區(qū)分計算機上不同服務盆犁;是一個數(shù)字范圍是0-65535,
但是其中1024以下的是著名端口,用來表示一些特殊的服務乙各,一般不要用
同一時間一個端口只能對應一個服務
server.bind(('10.7.187.130',8082))
3.開始監(jiān)聽
listen(最大監(jiān)聽數(shù))
最大監(jiān)聽數(shù)-用來設置當前服務器一次可以處理多少請求
server.listen(100)
print('開始監(jiān)聽')
4.讓服務器一直處于啟動狀態(tài)
`
while True:
接收客戶端發(fā)送的請求墨礁,返回客戶端地址和建立的會話;
注意耳峦,這段代碼會阻塞線程(程序到這回停下來恩静,直到有客戶端給當前服務器發(fā)送請求為止)
conversation,addr = server.accept()
print('接受請求',addr)
接受消息
recv(緩存大小) - 獲取客戶端給服務器發(fā)送的數(shù)據(jù),返回值是二進制
緩存大小-決定一次可以接收的最大字節(jié)數(shù)
re_data = conversation.recv(1024)
print(re_data)
## 7.fa送數(shù)據(jù)
send(數(shù)據(jù))-將制定數(shù)據(jù)發(fā)送給客戶端
數(shù)據(jù) - 要求是二進制
字符串(str)轉(zhuǎn)二進制(bytes)
bytes(字符串,'utf-8')
字符串.encode('utf-8')
二進制轉(zhuǎn)字符串
str(二進制數(shù)據(jù)蹲坷,'utf-8')
二進制.decode('utf-8')
message = '589554'
conversation.send(bytes(message),encoding='utf-8')
conversation.send(message.encode(encoding='utf-8'))
03-客戶端套接字
import socket
創(chuàng)建客戶端套接字
client = socket.socket()
2.lianjie服務器
connect(ip,端口)
client.connect(('10.7.187.133',8080))
3.fa送消息
while 1:
message = input()
client.send(message.encode('utf-8'))
# 接收消息
re_data = client.recv(1024)
print('服務器',re_data.decode('utf-8'))
04-服務器
import socket
server = socket.socket()
server.bind(('10.7.187.130',8824))
server.listen(1024)
while 1:
conversation,addr = server.accept()
while 1:
re_data = conversation.recv(1024)
# if not re_data:
# break
print('客戶端',re_data.decode('utf-8'))
message = input()
conversation.send(message.encode('utf-8'))
05-網(wǎng)絡請求
import requests
python中做HTTP請求需要一個第三方庫驶乾;request
get(url,參數(shù)字典)-返回響應
1.向服務器發(fā)送get請求
自動拼接url
# url = 'https://www.apiopen.top/satinApi?type=1&page=1 '
# response = requests.get(url)
# print(response)
# 手動拼接url
url = 'https://www.apiopen.top/satinApi'
response = requests.get(url,{'type':1,'page':1})
print(response)
2.獲取響應頭
header = response.headers
print(header)
# 獲取響應體
# 二進制格式響應頭
content = response.content
print(content,(content))
# 獲取json格式響應體 - 自動將json數(shù)據(jù)轉(zhuǎn)換成Python數(shù)據(jù)
json = response.json()
print(json,type(json))
# 獲取字符串格式響應體
text = response.text
print(text,type(text))
# url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b10000_10000&sec=1543395098&di=2a5bbaa5600097b050ba69a688672de9&src=http://p0.qhimgs4.com/t0112e7ebfdef7f923d.jpg '
url='http://wimg.spriteapp.cn/picture/2018/1114/9be9a9aee81811e8baee842b2b4c75ab_wpd.jpg'
response = requests.get(url)
image = response.content
with open('老王.jpg','wb')as f:
f.write(image)
8.關(guān)閉鏈接
conversation.close()