好像好久都没更博文了,没办法,最近各种倒霉事情,搞到最近真的没什么心情,希望之后能够转运吧。
言归正传,这次我要做的是基于序列化技术的socket文件传输来无聊练一下手。
一.socket文件传输
之前我所做的服务器和客户端的tcp/udp通信都是以字符串流来进行单工的,双工的传输,其实关于文件传输的原理也差不多,我的主要方法是通过文件迭代器遍历文件流,并将其读取转化为字符串流,然后将字符串流从服务器端发送,然后客户端在缓冲区中接收数据流,然后并把它写入文件当中,从而实现文件的传输,在下面程序当中,我仅仅是实现由服务器分发,客户端除了接收什么都不做的简单程序。
服务器端:
#!/usr/bin/env python#-*- coding:utf-8 -*-
from socket import *
from time importctimeimportos
HOST= ''PORT= 21567BUFSIZ= 4096ADDR=(HOST,PORT)
tcpSerSock=socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
filename= raw_input('Please input the file name:')whileTrue:print 'waiting for connection...'tcpCliSock,addr=tcpSerSock.accept()print '...connected from:',addrprint '向客户端发送文件...'f= open(filename,'r')for eachLine inf:
tcpCliSock.send('%s' %eachLine)
f.close()
tcpCliSock.close()print 'Done!'tcpSerSock.close()
客户端:
#!/usr/bin/env python#-*- coding:utf-8 -*-
from socket import *HOST= 'localhost'PORT= 21567BUFSIZ= 4096ADDR=(HOST,PORT)
tcpCliSock=socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)
filename= raw_input('Please input the filename you will write to:')
f= open(filename,'a') #以追加模式打开文件
print '正在写文件....'
whileTrue:
data=tcpCliSock.recv(BUFSIZ)if notdata:breakf.write(data)
f.close()print 'Done!'tcpCliSock.close()
还有一种比较方便的方法是用框架SocketServer来实现文件传输的功能,相当于重新实现linux的scp命令。
服务器端:
#!/usr/bin/env python#-*-coding:utf-8-*-
importSocketServer
addr= ('',21568)classDocHandler(SocketServer.StreamRequestHandler):defhandle(self):
doc_len= ord(self.rfile.read(1)) #文件的第一个字符代表文件名的长度
name =self.rfile.read(doc_len)print "接收文件:%s" %name
f= open('../'+name,'w')
cont= self.rfile.read(4096)whilecont:
f.write(cont)
cont= self.rfile.read(4096)
f.close()print "D