【python】TCP/IP编程
No1:
【TCP】
客户端
import 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: 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)
运行结果得到一个sina.html文件,双击打开是新浪主页
服务端接受客户端
import socket,threading s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind(('127.0.0.1',9999)) s.listen(5) print('Waiting for connection...') def tcplink(sock,addr): print('Accept new connection from %s:%s...' % addr) sock.send(b'Welcome!') while True: data = sock.recv(1024) time.sleep(1) if not data or data.decode('utf-8')=='exit': break sock.send(('Hello,%s' % data.decode('utf-8')).encode('utf-8')) sock.close() print('Connection from %s:%s closed.' % addr) while True: sock,addr = s.accept() t=threading.Thread(target=tcplink,args=(sock,addr)) t.start()
import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(('127.0.0.1',9999)) print(s.recv(1024).decode('utf-8')) for data in [b'Michael',b'Tracy',b'Sarah']: s.send(data) print(s.recv(1024).decode('utf-8')) s.send(b'exit') s.close()
No2:
【UDP】
服务端接受客户端
import socket s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind(('127.0.0.1',9999)) print('Bind UDP on 9999....') while True: data,addr=s.recvfrom(1024) print('Received from %s:%s.' % addr) s.sendto(b'Hello,%s!' % data,addr)
import socket s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) for data in [b'Michael',b'Tracy',b'Sarah']: s.sendto(data,('127.0.0.1',9999)) print(s.recv(1024).decode('utf-8')) s.close()
运行结果
No3:
【SMTP发送邮件】
构造一个邮件对象就是一个Messag
对象,如果构造一个MIMEText
对象,就表示一个文本邮件对象,如果构造一个MIMEImage
对象,就表示一个作为附件的图片,要把多个对象组合起来,就用MIMEMultipart
对象,而MIMEBase
可以表示任何对象。
from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr,formataddr import smtplib def _format_addr(s): name,addr=parseaddr(s) return formataddr((Header(name,'utf-8').encode(),addr)) from_addr=input('From:') password=input('Password:') to_addr=input('To:') smtp_server=input('SMTP server:') msg=MIMEText('hello,send by Python...','plain','utf-8') msg['From']=_format_addr('Python爱好者<%s>' % from_addr) msg['To']=_format_addr('管理员<%s>' % to_addr) msg['Subject']=Header('来自SMTP的问候。。。','utf-8').encode() server=smtplib.SMTP(smtp_server,25) server.set_debuglevel(1) server.login(from_addr,password) server.sendmail((from_addr,[to_addr],msg.as_string())) server.quit()
发送附件
msg=MIMEMultipart() msg['From']=_format_addr('Python爱好者<%s>'%from_addr) msg['To']=_format_addr('管理员<%s>'%to_addr) msg['Subject']=Header('来自SMTP的问候。。。','utf-8').encode() msg.attach(MIMEText('send with file...','plain','utf-8')) with open('/Users/michael/Download/test.png','rb') as f: mime=MIMEBase('image','png',filename='test.png') mime.add_header('Content-Disposition','attachment',filename='test.png') mime.add_header('Content-ID','<0>') mime.add_header('X-Attachment-Id','0') mime.set_payload(f.read()) encoders.encode_base64(mime) msg.attach(mime)
No4:
【Pop3接收邮件】
Python的poplib
模块收取邮件分两步:第一步是用POP3协议把邮件获取到本地,第二步是用email
模块把原始邮件解析为Message
对象,然后,用适当的形式把邮件内容展示给用户即可。
先接收
import poplib email=input('Email:') password=input('Password:') pop3_server=input('POP3 server:') server=poplib.POP3(pop3_server) server.set_debuglevel(1) print(server.getwelcome().decode('utf-8')) server.user(email) server.pass_(password) print('Message:%s. Size:%s' % server.stat()) resp,mails,octets=server.list() print(mails) index=len(mails) resp,lines,octets=server.retr(index) msg_content=b'\r\n'.join(lines).decode('utf-8') msg=Parser().parsestr(msg_content) server.quit()
再解析
from email.parser import Parser from email.header import decode_header from email.utils import parseaddr import poplib msg=Parser().parsestr(msg_content) def print_info(msg,indent=0): if indent==0: for header in ['From','To','Subject']: value=msg.get(header,'') if value: if header == 'Subject': value = decode_str(value) else: hdr,addr=parseaddr(value) name=decode_str(hdr) value=u'%s<%s>' % (name,addr) print('%s%s: %s' % (' ' * indent,header,value)) if(msg,is_multipart()): parts=msg.get_payload() for n,part in enumerate(parts): print('%spart %s' % (' ' * indent,n)) print('%s------------------' % (' ' * indent)) print_info(part,indent+1) else: content_type=msg.get_content_type() if content_type=='text/plan' or content_type=='text/html': content=msg.get_payload(decode=True) charset=guess_charset(msg) if charset: content=content.decode(charset) print('%sText: %s' % (' ' * indent,content + '...')) else: print('%sAttachment: %s' % (' ' * indent,content_type)) def decode_str(s): value,charset = decode_header(s)[0] if charset: value = value.decode(charset) return value def guess_charset(msg): charset=msg.get_charset() if charset is None: content_type=msg.get('Content-Type','').lower() pos=content_type.find('charset=') if pos >= 0: charset=content_type[pos + 8].strip() return charset