chouliqingke 2020-03-01
使用socket中的struck来实现客户端发送
服务端:
# -*- coding: UTF-8 -*- import socket, time, socketserver, struct, os, _thread host = ‘127.0.0.1‘ port = 12307 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 定义socket类型 s.bind((host, port)) # 绑定需要监听的Ip和端口号,tuple格式 s.listen(1) def conn_thread(connection, address): while True: try: connection.settimeout(600) fileinfo_size = struct.calcsize(‘12sl‘)#12s表示12个字符,l表示一个长整型数 buf = connection.recv(fileinfo_size) if buf: # 如果不加这个if,第一个文件传输完成后会自动走到下一句,需要拿到文件大小信息才可以继续执行 filename, filesize = struct.unpack(‘12sl‘, buf) filename_f = filename.decode("utf-8").strip(‘\00‘) # C语言中’\0’是一个ASCII码为0的字符,在python中表示占一个位置得空字符 filenewname = os.path.join(‘e:\\‘, os.path.basename(filename_f)) print(u‘文件名称:%s , 文件大小: %s‘ % (filenewname, filesize)) recvd_size = 0 # 定义接收了的文件大小 file = open(filenewname, ‘wb‘) print(u"开始传输文件内容") 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‘) # connection.close() except socket.timeout: connection.close() while True: print(u"开始进入监听状态") connection, address = s.accept() print(‘Connected by ‘, address) # thread = threading.Thread(target=conn_thread,args=(connection,address)) #使用threading也可以 # thread.start() _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) s.connect((‘127.0.0.1‘, 12307)) while True: filepath = input(‘请输入要传输的文件绝对路径:\r\n‘) print(type(filepath)) print(len(filepath.encode("utf-8"))) if os.path.isfile(filepath): #fileinfo_size = struct.calcsize(‘20sl‘) # 定义打包规则 # 定义文件头信息,包含文件名和文件大小 fhead = struct.pack(‘12sl‘, filepath.encode("utf-8"), os.stat(filepath).st_size) print(os.stat(filepath).st_size) s.send(fhead) print (u‘文件路径: ‘, filepath) # with open(filepath,‘rb‘) as fo: 这样发送文件有问题,发送完成后还会发一些东西过去 fo = open(filepath, ‘rb‘) while True: filedata = fo.read(1024) if not filedata: break s.send(filedata) fo.close() print (u‘传输成功‘) # s.close()
服务端效果:
客户端效果