此代码是客户端发往服务器端,是单向的
服务器端:
#服务器端(接收)
#-*- coding: UTF-8 -*-
import socket,time,SocketServer,struct,os,thread
host='192.168.56.1'
port=1234
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #定义socket类型
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
#用bind();listen();
s.bind((host,port))
s.listen(1)
i = 696
def conn_thread(connection,address):
global i
while True:
try:
connection.settimeout(1200)
fileinfo_size=struct.calcsize('=128sl')
buf = connection.recv(fileinfo_size)
if buf: #如果不加这个if,第一个文件传输完成后会自动走到下一句
print 1
filename,filesize =struct.unpack('=128sl',buf)
print 2
filename_f = filename.strip('\00')
j = i
filenewname = filename_f + '_' +str(j)
i = i + 1
print 'file new name is %s, filesize is %s' %(filenewname,filesize)
recvd_size = 0 #定义接收了的文件大小
file = open(filenewname,'wb')
print 'stat receiving...'
while not recvd_size == filesize:
if filesize - recvd_size > 1024:
rdata = connection.recv(1024)
recvd_size += len(rdata)
else:
rdata = connection.recv(filesize - recvd_size)
recvd_size = filesize
file.write(rdata)
file.close()
print 'receive done'
except socket.timeout:
connection.close()
while True:
connection,address=s.accept()
print('Connected by ',address)
thread.start_new_thread(conn_thread,(connection,address))
s.close()
#客户端(发送)
#客户端
#-*- coding: UTF-8 -*-
import socket,os,struct
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#客户端用connect(IP,端口)
s.connect(('192.168.56.1',1234))
def Send():
filepath = "C:\\xubing\\record\\record"
if os.path.isfile(filepath):
fileinfo_size=struct.calcsize('128sl') #定义打包规则
#定义文件头信息,包含文件名和文件大小
fhead = struct.pack('128sl',os.path.basename(filepath),os.stat(filepath).st_size)
s.send(fhead)
fo = open(filepath,'rb')
while True:
filedata = fo.read(1024)
if not filedata:
break
s.send(filedata)
fo.close()
print 'send over...'