TCP编程-访问别的服务器
import socket
‘’’
#创建socket对象
参数一:指定的ip协议 ipv4协议
参数二:指定的tcp协议
‘’’
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
‘’’
#创建连接
address地址,以元组的形式传递
域名/ip地址 端口号
网页的端口 80
STMP服务端口 25
‘’’
sock.connect((“www.zxxk.com”,80))
‘’’
发送请求,要求发送的数据必须是二进制的
‘’’
sock.send(b’GET / HTTP/1.1\r\nHost:www.zxxk.com\r\nConnection:close\r\n\r\n’)
data = b""
while True:
strb = sock.recv(1024)
if strb == b"":
break
data += strb
data = data.decode(“gbk”)
print(type(data))
datalist = data.split("\r\n\r\n\r\n",maxsplit=1)
with open(“head.txt”,“w”,encoding=“utf-8”) as f:
f.write(datalist[0])
with open(“zxxk.html”,“w”,encoding=“gbk”) as f2:
f2.write(datalist[-1])
sock.close()
需求:将获取到的内容分为两个部分,
上面的部分存储到head.txt中
下面的部分存储到zxxk.html中
TCP编程服务器
import socket
参数一:指定IP协议
参数二:指定tcp协议
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
绑定地址
地址是一个元组(ip地址,端口号)
sock.bind((“10.36.143.33”,9080))
#设置最大监听个数
sock.listen(7)
while True:
# 等待客户端的链接
此方法返回两个值
第一个值创建好的socket对象,第二个值就是地址
s,address = sock.accept()
while True:
data = s.recv(1024).decode("utf-8")
print(data)
if data == "bye":
break
redata = input("请回复信息:")
s.send(redata.encode("utf-8"))
TCP编程服务器
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((“10.36.143.33”,9080))
while True:
data = input(“输入发送的信息:”)
s.send(data.encode(“utf-8”))
if data == “bye”:
break
print(s.recv(1024).decode(“utf-8”))
s.close()
udp服务器
import socket
‘’’
参数一:指定ip协议
参数二:指定udp协议
‘’’
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind((“10.36.151.41”,8989))
while True:
data,address = sock.recvfrom(1024)
print(data,address)
sock.sendto(“收到”.encode(“utf-8”),address)
udp客户端
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.sendto(b"hello",(“10.36.151.41”,8989))
print(s.recv(1024).decode(“utf-8”))
s.close()
邮件发送
#发邮件的库
import smtplib
#邮件文本
from email.mime.text import MIMEText
#SMTP服务器
SMTPServer = ‘smtp.163.com’
#发邮箱的地址
sender = ‘[email protected]’
#发送者邮箱密码:授权码
password = ‘1q2w3e’
#设置发送文本的内容
message = ‘hello world’
#转为邮件文本
msg = MIMEText(message)
#标题
msg[‘Subject’] = ‘都挺好’
#发送者
msg[‘From’] = sender
#收件人
msg[‘To’] =‘[email protected]’
#打开SMTP服务器,端口号一般为25
mailServer = smtplib.SMTP(SMTPServer,25)
#登录邮箱
mailServer.login(sender,password)
#发送邮件
mailServer.sendmail(sender,[‘[email protected]’],msg.as_string())
#退出邮箱
mailServer.quit()