import socket
import ssl
def https_test(url):
proto = "http"
host = ""
port = 80
up = urlparse(url)
if (up.scheme != ""):
proto = up.scheme
print "proto=%s"%proto
dest = up.netloc.split(":")
if (len(dest) == 2):
port = int(dest[1])
else:
if (proto == "http"):
port = 80
elif (proto == "https"):
port = 443
host = dest[0]
if (proto == "http"):
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
elif (proto == "https"):
sock = ssl.wrap_socket(socket.socket())
sock.settimeout(5)
try:
sock.connect((host, port))
except Exception as e:
print ("error %s"%e)
return None
sock.send("GET %s HTTP/1.1\r\nHost: %s\r\n" %(up.path, host))
response = sock.recv(1024)
print response
sock.close()
客户端(TCP)编程:
举个例子,当我们在浏览器中访问新浪时,我们自己的计算机就是客户端,浏览器会主动向新浪的服务器发起连接。如果一切顺利,新浪的服务器接受了我们的连接,一个TCP连接就建立起来的,后面的通信就是发送网页内容了。
(1)我们要创建一个基于TCP连接的Socket,可以这样做(假设要访问的是https网页):
import socket
import ssl
s = ssl.wrap_socket(socket.socket())
s.connect(('www.sina.com.cn', 443))
s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')
buffer = []
while True:
d = s.recv(1024)
if d:
buffer.append(d)
else:
break
data = b''.join(buffer)
s.close()
header, html = data.split(b'\r\n\r\n', 1)
print(header.decode('utf-8'))
with open('sina.html', 'wb') as f:
f.write(html)
(2)我们要创建一个基于TCP连接的Socket,可以这样做(假设要访问的是http网页):
import socket
# 创建一个socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接:
s.connect(('www.sina.com.cn', 80))
# 发送数据:
s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')
# 接收数据:
buffer = []
while True:
# 每次最多接收1k字节:
d = s.recv(1024)
if d:
buffer.append(d)
else:
break
data = b''.join(buffer)
# 关闭连接:
s.close()
header, html = data.split(b'\r\n\r\n', 1)
print(header.decode('utf-8'))
# 把接收的数据写入文件:
with open('sina.html', 'wb') as f:
f.write(html)