综述:大概比较厉害的人都要写点东西吧,咱不是什么牛人,但咱总要向牛人的方向靠拢啊,不然可能会被社会淘汰了。有人说技术改变世界,在我看来学点技术也不是什么坏事。
先说说我写博客的初衷吧。我自己就是个比较懒惰和懒散的人,总是想的多、做得少,俗话说好记性不如烂笔头,就算一个人记忆力再好,也有记不住的东西。所以有必要把值得记下的东西写下来,以后看看或许还能找到当初的感觉,算是给自己一个交代吧。
最近找了个实习,由于业务需要,导师让我学学python。之前就听说过python这个语言,什么hacker的必备语言、什么代码非常简洁、什么life is short, i use python 云云... 正好我也不知道编程该从哪里开始学起,就按照导师的思路走吧。
1.我看的参考书是《dive into python》,用的环境是xshell+cenos虚拟机,翻墙用google查资料
2.第一个python程序是写一个基于socket的c/s模型,可以实现文件的上传和下载:
先附上源码:
ftp_client.py
#coding=utf-8 import socket import os import time import sys if len(sys.argv) != 2: print ‘\n‘,‘Using python‘,sys.argv[0],‘server_ip:port‘ server = (‘127.0.0.1‘,8080) else: server = sys.argv[1].split(‘:‘) server = (server[0],int(server[1])) sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) print ‘Connecting...‘ sock.connect(server) print ‘Connected to %s:%d‘ %server while True: data = raw_input(‘unload or download: u/d\t‘) data = data.strip() if not data: break if data == ‘u‘: fp = ‘‘ sock.send(data) flist = os.listdir(‘.‘) for f in flist: print ‘%d.%s‘%(flist.index(f) + 1,f) fname = raw_input(‘\nEnter a filename to upload: ‘).strip() try: index = int(fname) if type(index) is int: fname = flist[index - 1] except: pass fp = open(fname,‘rb‘) fsize = os.path.getsize(fname) if not fp: continue sock.send(fname + ‘:‘ + str(fsize)) print ‘Start uploading...‘ time.sleep(0.1) while True: fsend = fp.read(1024) if not fsend: break sock.send(fsend) fp.close() print ‘Upload complete!‘,‘\n‘ if data == ‘d‘: sock.send(data) flist = sock.recv(1024).split(‘;‘) fname = [] fsize = [] for f in flist: fname.append(f.split(‘:‘)[0]) fsize.append(str(f.split(‘:‘)[1])) flist = fname for f in flist: print ‘%d.%s‘%(flist.index(f) + 1,f) fname = raw_input(‘\nEnter a filename to download: ‘).strip() try: index = int(fname) if type(index) is int: fname = flist[index - 1] except: pass if fname not in flist: print ‘File doesn\‘t exit!‘ continue sock.send(fname) fsize = int(fsize[flist.index(fname)]) print ‘Start downloading...‘ if fname in os.listdir(‘.‘): oldfname = fname fname = raw_input(‘File exit, saving as [Default new_%s]:‘ %fname) if not fname: fname = ‘new_‘ + oldfname while fname in os.listdir(‘.‘): fname = ‘new_‘ + fname fp = open(fname,‘wb‘) while True: frecv = sock.recv(1024) frecvsize = len(frecv) fsize -= frecvsize fp.write(frecv) if fsize <= 0: break print fname,‘Downloaded from %s:%d‘ %server,‘\n‘ fp.close()
ftp_server.py
#coding=utf-8 import socket,os,threading,time,sys if len(sys.argv) != 2: print ‘\n‘,‘Using: python‘,sys.argv[0],‘server_ip:port‘ server = (‘127.0.0.1‘,8080) else: server = sys.argv[1].split(‘:‘) server = (server[0],int(server[1])) class MyThread(threading.Thread): def __init__(self,conn,addr): threading.Thread.__init__(self) self.conn = conn self.addr = addr def run(self): while True: data = self.conn.recv(1024).strip() if not data: break if data == ‘u‘: fhead = self.conn.recv(1024).split(‘:‘) fname,fsize = (fhead[0],int(fhead[1])) print ‘fname : %s, fsize : %d‘ %(fname,fsize) if not fname: continue while fname in os.listdir(‘.‘): fname = ‘new_‘+fname print ‘Saving as:‘,fname fp = open(fname,‘wb‘) while True: frecv = self.conn.recv(1024) frecvsize = len(frecv) fsize -= frecvsize fp.write(frecv) if fsize <= 0:break print fname,‘Uploaded by %s:%d‘ %self.addr,‘\n‘ fp.close() if data == ‘d‘: flist = os.listdir(‘.‘) for f in flist: flist[flist.index(f)] = f + ‘:‘ + str(os.path.getsize(f)) flist = ‘;‘.join(flist) self.conn.send(flist) fname = self.conn.recv(1024).strip() if not fname: continue fp = open(fname,‘rb‘) while True: fsend = fp.read(1024) if not fsend: break self.conn.send(fsend) fp.close() print fname,‘Sent to %s:%d‘ %self.addr,‘\n‘ self.conn.close() def main(): sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.bind(server) print ‘Server starts: %s:%d‘ %(server[0],server[1]) sock.listen(5) threads = [] while True: conn,addr = sock.accept() print ‘Connected to %s:%d‘ %addr t = MyThread(conn,addr) t.start() sock.close() if __name__ == ‘__main__‘: main()
3.下面是基于http协议的服务器,可以下载当前目录下的文件
http_server.py
#coding=utf-8 import socket import os import sys import time import threading server = (‘127.0.0.1‘,80) def printusage(): ‘‘‘ Set server to default or user definition‘‘‘ global server if len(sys.argv) != 2: print ‘\n‘,‘Usage: python‘,sys.argv[0],‘server_ip:port‘ print ‘eg. : python 192.68.0.1:80‘ print ‘default : 127.0.0.1:8080‘ server = (‘127.0.0.1‘,8080) else: server = sys.argv[1].split(‘:‘) server = (server[0],int(server[1])) class Http(): ‘‘‘ My Http calss‘‘‘ def __init__(self): self.html_head = ‘HTTP/1.x 200 OK\r\n‘ + ‘Content-Type: text/html\r\n\r\n‘ self.html_body = ‘‘ self.filedata = ‘‘ def getindex(self): ‘‘‘ Get index.html information‘‘‘ self.html_body = ‘‘‘ <html> <title>Http Server Powered by Python</title> <head><b>Choose a file to download</b></head> <body> <br /><br /> ‘‘‘ flist = os.listdir(‘.‘) i = 1 for f in flist: self.html_body += ‘<a href=\‘http://%s:%d/%d.%s\‘ style=\"text-decoration:none\"> <b>%d.%s</b></a><br />\n‘ %(server[0],server[1],i,f,i,f) i += 1 self.html_body += ‘</body></html>‘ def getfiledata(self,filename,fheadsize,readsize): ‘‘‘ Read file and save to Http.filedata‘‘‘ fp = open(filename,‘rb‘) fsize = os.path.getsize(filename) if fheadsize == 0: code = ‘200 OK‘ filedata_head = ‘HTTP/1.1 %s\r\n‘ %code + ‘Content-Type: application/octet-stream\r\n‘ + ‘Content-Length: %d\r\n‘ %fsize + ‘Connection: keep-alive\r\n‘ + ‘Content-Disposition: attachment; filename=\"%s\"\r\n‘ %filename + ‘Accept-Ranges: bytes\r\n‘ + ‘Content-Ranges: bytes=%d-%d/%d\r\n\r\n‘ %(fheadsize,fheadsize + readsize,fsize) else: filedata_head = ‘‘ fp.seek(fheadsize,0) filedata_body = fp.read(readsize) fp.close() self.filedata = filedata_head + filedata_body class HttpThread(threading.Thread): ‘‘‘ Http threads, to deal with file-downloads‘‘‘ def __init__(self,conn,addr,filename): threading.Thread.__init__(self) self.conn = conn self.addr = addr self.filename = filename def run(self): ‘‘‘ Threads‘ function‘‘‘ if self.filename in os.listdir(‘.‘): ‘‘‘ Deal with client request /filename resource‘‘‘ myhttp = Http() buffsize = 1024 fsize = os.path.getsize(self.filename) fheadsize = 0 while True: if fsize - fheadsize > buffsize: readsize = buffsize if fsize - fheadsize <= buffsize: readsize = fsize - fheadsize if fheadsize >= fsize: break myhttp.getfiledata(self.filename,fheadsize,readsize) fheadsize += readsize try: self.conn.send(myhttp.filedata) except socket.error: print ‘Client closed connection!‘ self.conn.close() return self.conn.close() print ‘Send %s to %s:%d done!\n‘ %(self.filename,self.addr[0],self.addr[1]) self.conn.close() def createsock(): ‘‘‘ Create socket and return sock‘‘‘ sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.bind(server) print ‘Server starts: %s:%d‘ %server sock.listen(5) return sock def readfile(filename): ‘‘‘ Read file‘‘‘ if filename == ‘index.html‘: myhttp = Http() myhttp.getindex() return myhttp.html_head + myhttp.html_body def getfilename(conn): ‘‘‘ Get filename from client‘‘‘ data = conn.recv(1024) filename = ‘‘ try: data = data.split(‘ ‘)[1] filename = data.split(‘.‘,1)[1] except: pass if not filename: filename = ‘index.html‘ return filename def main(): ‘‘‘ Deal with client request‘‘‘ printusage() sock = createsock() while True: conn,addr = sock.accept() print ‘Connected to %s:%d‘ %addr filename = getfilename(conn) if filename == ‘index.html‘: ‘‘‘ Deal with client request / resource‘‘‘ conn.sendall(readfile(filename)) conn.close() continue if filename in os.listdir(‘.‘): ‘‘‘ Deal with client request /filename resource Open a new thread to read file and send data ‘‘‘ myhttpthread = HttpThread(conn,addr,filename) myhttpthread.start() continue sock.close() if __name__ == ‘__main__‘: main()
时间: 2024-09-28 22:34:54